SQL 透视反透视查询

SQL pivot unpivot query

我对 pivot/unpivot 没有太多经验,需要一些帮助。我有一个 SQL 查询,数据为:

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

我需要它显示为:

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

我该怎么做?

谢谢, 玛西

一种方法是使用条件聚合:

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

我只想按

分组
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

请注意,如果不止一行具有相同的类别、帐户和名称,这将失败 -- 但您没有告诉我们如何处理。