0

I have a table like this:

DateKey   | Category  |  Value 
----------+-----------+---------
20190102  | CAT1      | 12
20190502  | CAT2      | 13
20190502  | CAT2      | 16
20190102  | CAT1      |  2
20190102  | CAT3      | 22
....

I want to get a result like this.

The columns are automatically generated from the SQL statement

DateKey   | CAT1SUM   |  CAT2SUM  |  CAT3SUM
----------+-----------+-----------+-----------
20190102  | 14        |  0        | 22
20190502  |  0        | 29        |  0

I know how to do this with known Categories, but the problem is Category amount are unknown, but the amount are not too many ( less than 20). I know that I can write a store procedure / function, but Is it possible to archive this in as few sql statement as possible? What is the most efficient way to do it?

I know I can get a single column table like this

SELECT 
    DateKey, Category, SUM(Value) SummedValue
FROM 
    MyTable
GROUP BY 
    DateKey, Category

But, the result is a single 'value' column table, which is not what I want.

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
Tony
  • 632
  • 1
  • 4
  • 18

0 Answers0