动态数据透视查询

时间:2012-06-27 05:54:18

标签: sql sql-server

以下查询执行得很好......

select LIC,PF from (select * from tbl_DeductionHead )up
pivot(sum(DeductionPerAmount) for DeductionHead In (LIC,PF)) as pvt

和输出看起来像,

LIC PF
900.00 NULL 
NULL 600.00

但我怀疑的是我如何才能获得动态栏的字段值..

select * from (select * from tbl_DeductionHead )up
pivot(sum(DeductionPerAmount) for DeductionHead In (*)) as pvt

如何使用上述查询

1 个答案:

答案 0 :(得分:2)

要使PIVOT动态化,您必须编写存储过程。

CREATE PROCEDURE dynPivot 
(
@select varchar(255), 
@pivotColumns varchar(255), 
@summaries varchar(100) 
) AS 

DECLARE @pivot varchar(max), @sql varchar(max), @selectForPivotColumns varchar(max)

SELECT @selectForPivotColumns = REPLACE(@select, 'SELECT', 'SELECT ' + @pivotColumns + ' AS rowValuesToColumns, ')

CREATE TABLE #pivot_columns (pivot_column varchar(100))

SELECT @sql = 'SELECT DISTINCT rowValuesToColumns FROM (' + @selectForPivotColumns + ') as t'

INSERT INTO #pivot_columns
EXEC(@sql)

SELECT @pivot = COALESCE(@pivot + ', ', '') + '[' + pivot_column + ']' FROM #pivot_columns

SELECT @sql = 
'
    SELECT * FROM
    (
        ' + @select + '
    ) AS t
    PIVOT
    (
        ' + @summaries + ' FOR ' + @pivotColumns + ' IN (' + @pivot + ')
    ) AS p
'

EXEC(@sql)

然后你可以这样称呼它:

EXEC dynPivot 'SELECT * FROM tbl_DeductionHead', 'DeductionHead', 'SUM(DeductionPerAmount)';