[英]SQL pivot unpivot query
I don't have much experience with pivot/unpivot and could use some help. 我对pivot / unpivot没有多少经验,可以使用一些帮助。 I have a SQL query with data as :
我有一个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
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 谢谢,Marcie
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
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. 请注意,如果您有多个具有相同类别,帐户和名称的行,则会失败 - 但您没有告诉我们如何处理该行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.