小编典典

动态数据透视查询

sql

以下查询执行得很好…

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

如何使用以上查询


阅读 161

收藏
2021-04-07

共1个答案

小编典典

要使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)';
2021-04-07