1.行列转换
把图1的行转换为图2的列
使用2005自带函数 PIVOT
PIVOT用于将列值旋转为列名(即行转列),在SQL Server 2000可以用聚合函数配合CASE语句实现
PIVOT的一般语法是:PIVOT(聚合函数(列) FOR 列 in (…) )AS P
完整语法:
table_source
PIVOT(
聚合函数(value_column)
FOR pivot_column
IN(<column_list>)
)
UNPIVOT用于将列明转为列值(即列转行),在SQL Server 2000可以用UNION来实现
完整语法:
table_source
UNPIVOT(
value_column
FOR pivot_column
IN(<column_list>)
)
WITH ProductTable
AS ( SELECT VPIV.ProductID ,
DF.DataID ,
DirectionDrugNum = SUM(VCPSD.DirectionDrugNum)
FROM dbo.VProductInfoView VPIV ,
dbo.[UF_XA_GetDatePartTable_21](2, '2011-01-01',
'2011-12-31') DF ,
dbo.VCustomerProStockDetail VCPSD
WHERE VPIV.ProductID = VCPSD.ProductID
AND VCPSD.CustomerStockType = 0
AND VCPSD.BizDate >= DF.BeginDate
AND VCPSD.BizDate < DF.EndDate
GROUP BY VPIV.ProductID ,
DF.DataID
)
SELECT ProductID ,
[1] AS 一月 ,
[2] AS 二月 ,
[3] AS 三月 ,
[4] AS 四月 ,
[5] AS 五月 ,
[6] AS 六月 ,
[7] AS 七月 ,
[8] AS 八月 ,
[9] AS 九月 ,
[10] AS 十月 ,
[11] AS 十一月 ,
[12] AS 十二月 ,
ISNULL([1], 0) + ISNULL([2], 0) + ISNULL([3], 0) + ISNULL([4], 0)
+ ISNULL([5], 0) + ISNULL([6], 0) + ISNULL([7], 0) + ISNULL([8], 0)
+ ISNULL([9], 0) + ISNULL([10], 0) + ISNULL([11], 0) + ISNULL([12],
0) AS 累计
FROM ( SELECT VPIV.ProductID ,
VPIV.ProName ,
VPIV.ProStandard ,
VPIV.FactoryName ,
PT.DataID ,
PT.DirectionDrugNum
FROM dbo.VProductInfoView VPIV
LEFT JOIN ProductTable PT ON VPIV.ProductID = PT.ProductID
) A PIVOT
( SUM(A.DirectionDrugNum) FOR A.DataID IN ( [1], [2], [3], [4], [5], [6],
[7], [8], [9], [10], [11], [12] ) ) AS pvt ;
实现效果: