0

以下查询执行良好...

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

如何使用上述查询

4

1 回答 1

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)';
于 2012-06-27T11:17:21.777 回答