1

I don't have much experience with pivot/unpivot and could use some help. I have a SQL query with data as :

Category Account   Name           Value
001      1234     BALANCE_01      800
001      1234     BALANCE_02      1000
001      1234     BALANCE_03      1500
001      4567     BALANCE_01      900
001      4567     BALANCE_02      1200
001      4567     BALANCE_03      800

I need it to appear as:

Category Account   BALANCE_01  BALANCE_02  BALANCE_03
001       1234       800         1000         1500
001       4567       900         1200         800

How do I do this?

Thanks, Marcie

McNets
  • 9,869
  • 3
  • 31
  • 54
Marcie
  • 47
  • 1
  • 1
  • 6

2 Answers2

0

One way is to do this is by using conditional aggregation:

SELECT Category,
       Account,
       MAX(CASE WHEN Name = 'BALANCE_01' THEN Value ELSE NULL END) AS BALANCE_01,
       MAX(CASE WHEN Name = 'BALANCE_02' THEN Value ELSE NULL END) AS BALANCE_02,
       MAX(CASE WHEN Name = 'BALANCE_03' THEN Value ELSE NULL END) AS BALANCE_03
FROM Table
GROUP BY Category, Account
Aaron Dietz
  • 9,679
  • 1
  • 12
  • 24
0

I would just just a group by

SELECT Category, Account, 
       SUM(CASE WHEN NAME='BALANCE_1' THEN Value ELSE 0 END) AS BALANCE_1,
       SUM(CASE WHEN NAME='BALANCE_2' THEN Value ELSE 0 END) AS BALANCE_2,
       SUM(CASE WHEN NAME='BALANCE_3' THEN Value ELSE 0 END) AS BALANCE_3
FROM Your_Table_You_Did_Not_Name
GROUP BY Category, Account

Note, if you have more than one row with the same Category, Account and Name this will fail -- but you don't tell us how to handle that.

Hogan
  • 65,989
  • 10
  • 76
  • 113