以一张薪资表为例,表结构如下:
表结构中,每个员工id对应有多个薪资项目以及金额,需要查询时转向,将每个员工的薪资项目转为横向一行显示。
在直接查询(加入一些限制条件以缩小结果集),
SELECT
ssp_pay_empid,
ssp_pay_sdate,
ssp_pay_edate,
ssp_pay_type,
ssp_pay_amount,
ssp_pay_item
FROM ssp_pay
where ssp_pay_empid = 00000073 and ssp_pay_type = 'RT' and ssp_pay_item
IN ('/101','/103','/401','/402') and ssp_pay_sdate = '2007-08-01'
得到如下结果:
需要将上述查询结果显示为一行,则使用SQL Server 2005新增的PIVOT ,通过将表达式某一列中的唯一值转换为输出中的多个列来旋转表值表达式,并在必要时对最终输出中所需的任何其余列值执行聚合。
执行如下SQL:
select
ssp_pay_empid,
ssp_pay_sdate,
ssp_pay_edate,
ssp_pay_type,
[/101],
[/103],
[/401],
[/402]
from (
SELECT
ssp_pay_empid,
ssp_pay_sdate,
ssp_pay_edate,
ssp_pay_type,
ssp_pay_amount,
ssp_pay_item
FROM ssp_pay
where ssp_pay_empid = 00000073 and ssp_pay_type = 'RT' and ssp_pay_sdate = '2007-08-01'
) AS SourceTable
PIVOT (SUM(ssp_pay_amount) FOR ssp_pay_item
IN ([/101],[/103],[/401],[/402])) AS PivotTable
结果为:
以上为记录笔记,无他用。