0

I have this table: table

And I want to know if there is some SQL query to return something like this: result

I tried this but didn't work:

SELECT Object, 
       SUM(CASE WHEN Key = 'A' THEN Qty END) As Key A, 
       SUM(CASE WHEN Key = 'B' THEN Qty END) As Key B
FROM tab

And even added the GROUP BY clause but the error is at the CASE clause

a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843
  • Possible duplicate of [Inserting multiple rows in a single SQL query?](https://stackoverflow.com/questions/452859/inserting-multiple-rows-in-a-single-sql-query) – Dragutinovic Jun 20 '19 at 18:38

2 Answers2

1

I would expect something like this:

SELECT Object,
       SUM(CASE WHEN Key = 'A' THEN Qty END) As KeyA,
       SUM(CASE WHEN Key = 'B' THEN Qty END) As KeyB
FROM table  -- table won't work as a table name
GROUP BY object;

I added the GROUP BY and fixed the column aliases.

Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
0

add group by in your query as you execute the aggregation

    SELECT Object, 
   SUM(CASE WHEN Key = 'A' THEN Qty END) As Key_A,
   SUM(CASE WHEN Key = 'B' THEN Qty END) As Key_B
    FROM table group by Object

you have used space of column alias name i changed it

Zaynul Abadin Tuhin
  • 30,345
  • 5
  • 25
  • 56