我正在使用sql 2008 我的数据集看起来像
Entity Type1 Type2 Balance
1 A R 100
1 B Z 200
1 C R 300
2 A X 1000
2 B Y 2000
我的输出应该是
Entity A-Type2 A-Balance B-Type2 B-Balance C-Type2 C-Balance
1 R 100 Z 200 R 300
2 X 1000 Y 2000 0
现在我开始编写一个数据透视查询,我想我可以使用MAX,因为每个Entity / Type1组合应该有一条记录。但无法弄清楚如何在一个支点中做两个字段。这可能吗?这是CTE可以提供帮助的东西吗?
答案 0 :(得分:5)
最简单的是MAX的想法,但有一个CASE语句,例如:
SELECT
Entity,
MAX(CASE WHEN Type1 = 'A' THEN Type2 ELSE NULL END) AS AType2,
MAX(CASE WHEN Type1 = 'A' THEN Balance ELSE NULL END) AS ABalance,
MAX(CASE WHEN Type1 = 'B' THEN Type2 ELSE NULL END) AS BType2,
MAX(CASE WHEN Type1 = 'B' THEN Balance ELSE NULL END) AS BBalance,
MAX(CASE WHEN Type1 = 'C' THEN Type2 ELSE NULL END) AS CType2,
MAX(CASE WHEN Type1 = 'C' THEN Balance ELSE NULL END) AS CBalance
FROM
...
GROUP BY
Entity
换句话说,仅当Type1是特定值时使用该值(其他Type1值变为null)。
答案 1 :(得分:3)
您只需使用条件聚合进行旋转:
select Entity,
max(case when Type1 = 'A' then Type2 end) as A_Type2,
max(case when Type1 = 'A' then Balance else 0 end) as A_Balance,
max(case when Type1 = 'B' then Type2 end) as B_Type2,
max(case when Type1 = 'B' then Balance else 0 end) as B_Balance,
max(case when Type1 = 'C' then Type2 end) as C_Type2,
max(case when Type1 = 'C' then Balance else 0 end) as C_Balance
from MyDataSet mds
group by Entity;
答案 2 :(得分:0)
这是使用数据透视和查找来完成的。
SELECT
data.Entity,
ISNULL(a.Type2,'') AS [A-Type2],
ISNULL([A-Balance],0) AS [A-Balance],
ISNULL(b.Type2,'') AS [B-Type2],
ISNULL([B-Balance],0) AS [B-Balance],
ISNULL(c.Type2,'') AS [C-Type2],
ISNULL([C-Balance],0) AS [C-Balance]
FROM
(
SELECT
Entity,
A AS [A-Balance],
B AS [B-Balance],
C AS [C-Balance]
FROM
(
SELECT Entity, Type1, Balance FROM @table
) t
PIVOT (
MAX(Balance)
FOR Type1 IN ([A],[B],[C])
) piv
) data
LEFT OUTER JOIN @table a on a.Type1 = 'A'
AND a.Entity = data.Entity AND a.Balance = [A-Balance]
LEFT OUTER JOIN @table b on b.Type1 = 'B'
AND b.Entity = data.Entity AND b.Balance = [B-Balance]
LEFT OUTER JOIN @table c on c.Type1 = 'C'
AND c.Entity = data.Entity AND c.Balance = [C-Balance]