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

  • 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,242,037
  • 58
  • 646
  • 786
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
  • 31,407
  • 5
  • 33
  • 63