'Need help combining multiple row data from same field, into multiple columns with alias

I have this table (see below) with rows from same "id" but different "codes" Capital/Expense as shown below. Need to be able to generate an output that sums the "value" for Capital Codes and Expense Codes in two separate columns. I tried using Where and Alias but running into problems. My data view table name: budgetcell_view My data file is as shown below:

projectid code coodename fieldtypename value
6 01-00-000 capital cost1 325000
6 02-00-000 expense cost1 250000
7 01-00-000 capital cost1 200000
7 02-00-000 expense cost1 125000
8 01-00-000 capital cost1 400000
8 02-00-000 expense cost1 210000
9 01-00-000 capital cost1 550000
9 02-00-000 expense cost1 330000

my desired output is below.... any help will be appreciated:

projectid capital_value expense_value
6 325000 250000
7 200000 125000
8 400000 210000
9 550000 330000


Solution 1:[1]

In this specific case, you can simply create such a query using a case when construct:

SELECT projectid, 
SUM(CASE WHEN code = '01-00-000' THEN value ELSE 0 END) capital_value,
SUM(CASE WHEN code != '01-00-000' THEN value ELSE 0 END) expense_value
FROM table1
GROUP BY projectid ORDER BY projectid;

Please see the working example here: db<>fiddle Please note that you maybe need to extend this query or modify it if there are more difficult options (not only capital or expense), that's why I asked you to provide the entire table data.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonas Metzler