SQLServer 行列转换

从SQLServer2005 以后多了一个函数:PIVOT,相比SQLServer2000的行列转换要简单快捷得多。

PIVOT

PIVOT 运算符可用来处理开放架构方案以及生成交叉分析报表。

在开放架构方案中,您需要用事先不知道或因实体类型而异的属性集来维护实体。应用程序的用户动态定义这些属性。您将属性拆分到不同的行中,并且只为每个实体实例存储相关的属性,而不是在表中预定义很多列并存储很多空值。

PIVOT 使您可以为开放架构和其他需要将行旋转为列的方案生成交叉分析报表,并且可能同时计算聚合并且以有用的形式呈现数据。

 

 

下面做一个简单的例子:

例如我们想把数据:

SQLServer 行列转换_第1张图片

转换为:

 

这是个非常经典的转换,下面用简单的代码作为示例:

CREATE TABLE SalesByMonth
(
    year char(4),
    month char(3),
    amount MONEY,
    PRIMARY KEY(year,month)
)

INSERT INTO SalesByMonth(year,month,amount)
values('2007','Jan',789.0000),
      ('2007','Feb',389.0000),
      ('2007','Mar',8867.0000),
      ('2007','Apr',778.0000),
      ('2007','May',78.0000),
      ('2007','Jun',9.0000),
      ('2007','Jul',987.0000),
      ('2007','Aug',866.0000),
      ('2007','Sep',7787.0000),
      ('2007','Oct',85576.0000),
      ('2007','Nov',855.0000),
      ('2007','Dec',5875.0000),
      
      ('2008','Jan',7.0000),
      ('2008','Feb',6868.0000),
      ('2008','Mar',688.0000),
      ('2008','Apr',9897.0000)
      
SELECT YEAR,
       SUM(case when month='Jan' then amount else 0 end) as 'Jan',
       SUM(case when month='Feb' then amount else 0 end) as 'Feb',
       SUM(case when month='Mar' then amount else 0 end) as 'Mar',
       SUM(case when month='Apr' then amount else 0 end) as 'Apr',
       SUM(case when month='May' then amount else 0 end) as 'May',
       SUM(case when month='Jun' then amount else 0 end) as 'Jun',
       SUM(case when month='Jul' then amount else 0 end) as 'Jul',
       SUM(case when month='Aug' then amount else 0 end) as 'Aug',
       SUM(case when month='Sep' then amount else 0 end) as 'Sep',
       SUM(case when month='Oct' then amount else 0 end) as 'Oct',
       SUM(case when month='Nov' then amount else 0 end) as 'Nov',
       SUM(case when month='Dec' then amount else 0 end) as 'Dec'
FROM SalesByMonth 
group by year     

select YEAR,[Jan],[Feb],[Mar],[Apr],[May],[Jun],
            [Jul],[Aug],[Sep],[Oct],[Nov],[Dec]
FROM 
    (Select YEAR,amount,month from SalesByMonth) as SalesByMonth 
    pivot (sum(amount) for month in 
            (
                [Jan],[Feb],[Mar],[Apr],[May],[Jun],
                [Jul],[Aug],[Sep],[Oct],[Nov],[Dec]
            )) as ourPivot
order by year

 

你可能感兴趣的:(SQLServer 行列转换)