1

报告表

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 功能实现这一点

4

1 回答 1

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

于 2013-09-15T18:21:06.990 回答