有人可以帮我解决SQL 2005中的交叉表/数据透视查询
鉴于数据看起来像
EmpId OrgId DayCt Cost
1 20 15 100
2 20 36 300
3 40 25 200
4 40 10 50
结果如下:
EmpId OrgId 20 OrgId 40
DayCt Cost DayCt Cost
1 15 100
2 36 300
3 25 200
4 10 50
第一个Col的EmpId,然后是下一个col的Org Ids。但是在每个OrgId下,我都想要DayCt&成本也包括在子列中。不确定这是否可行。请帮忙。
答案 0 :(得分:1)
没有子列,这似乎应该在您的应用程序/报告工具中完成。
这是SQL中最接近的
;WITH T(EmpId,OrgId,DayCt,Cost) AS
(
select 1, 20, 15, 100 UNION ALL
select 2, 20, 36, 300 UNION ALL
select 3, 40, 25, 200 UNION ALL
select 4, 40, 10, 50
)
SELECT EmpId,
MAX(CASE WHEN OrgId =20 THEN DayCt END) AS [OrgId 20 DayCt],
MAX(CASE WHEN OrgId =20 THEN Cost END) AS [OrgId 20 Cost],
MAX(CASE WHEN OrgId =40 THEN DayCt END) AS [OrgId 40 DayCt],
MAX(CASE WHEN OrgId =40 THEN Cost END) AS [OrgId 40 Cost]
FROM T
GROUP BY EmpId
返回
EmpId OrgId 20 DayCt OrgId 20 Cost OrgId 40 DayCt OrgId 40 Cost
----------- -------------- ------------- -------------- -------------
1 15 100 NULL NULL
2 36 300 NULL NULL
3 NULL NULL 25 200
4 NULL NULL 10 50