JK1993
JK1993

Reputation: 138

SUM Values within SQL based on a column

I have a table like below:

enter image description here

I want to transform the data so that the end product actually looks like this:

enter image description here

This is easily done within Excel but i would like to be able to do this via SQL so i can automate a report.

I have tried the below code which doesn't work:

SELECT 
SKU,
SUM(totals,ordered = 'Web') as Web_orders,
SUM(totals,ordered = 'App') as App_orders

FROM A

GROUP BY SKU

Upvotes: 0

Views: 51

Answers (2)

Maurice Meyer
Maurice Meyer

Reputation: 18106

You can make use of case expressions:

SELECT
  sku,
  SUM(case when ordered = 'web' then totals else 0 end) as "web",
  SUM(case when ordered = 'app' then totals else 0 end) as "app"
FROM A
GROUP BY sku

Upvotes: 2

Bjarni Ragnarsson
Bjarni Ragnarsson

Reputation: 1781

This will work:

SELECT 
SKU,
SUM(totals) filter (where ordered='web') as Web_orders,
SUM(totals) filter (where ordered='app') as App_orders
FROM A

GROUP BY SKU
ORDER by SKU;

If you want the uppercase letters you need to surround the column names with "".

Upvotes: 2

Related Questions