报告表
Country | Report Section| Report Field | Report Value
--------------------------------------------------------
India | Section1 | No of Employees | 100
India | Section1 | No of Dept | 5
India | Section1 | No of Contractors| 10
India | Section2 | Avg. Working Hrs | 8
India | Section2 | Avg. Utilization | 80
India | Section2 | Avg. Pay | 200
China | Section1 | No of Employees | 110
China | Section1 | No of Dept | 4
China | Section1 | No of Contractors| 1
China | Section2 | Avg. Working Hrs | 10
China | Section2 | Avg. Utilization | 90
China | Section2 | Avg. Pay | 100
需要输出,如没有任何聚合函数
Report Section| Report Field | India | China
--------------------------------------------------------
Section1 | No of Employees | 100 | 110
Section1 | No of Dept | 5 | 4
Section1 | No of Contractors| 10 | 1
Section2 | Avg. Working Hrs | 8 | 10
Section2 | Avg. Utilization | 80 | 90
Section2 | Avg. Pay | 200 | 100
如何使用sql server PIVOT功能实现这一目标
答案 0 :(得分:1)
您必须使用pivot
select *
from Report as r
pivot(
max(r.[Report Value])
for r.Country in ([India], [China])
) as p
order by [Report Section]
您也可以在没有pivot
运算符的情况下执行此操作:
select
r.[Report Section], r.[Report Field],
max(case when r.Country = 'India' then r.[Report Value] end) as [India],
max(case when r.Country = 'China' then r.[Report Value] end) as [China]
from Report as r
group by r.[Report Section], r.[Report Field]
order by [Report Section];
<强> sql fiddle demo 强>