如何使查询从列中选择不同的值作为透视值?

时间:2018-03-14 17:25:41

标签: sql-server pivot

查询:

select employee_sk,
[201701],
[201702] 
 from

(select Employee_SK, Period_NK, CalcClinical_FTE  from cmgr.FACT_Payroll) as sourcetable

pivot
(
sum(CalcClinical_FTE)
for period_nk
in ([201701],[201702])
) as a

我在period_nk列中有多个句点,范围从201401到201801。 那么,我如何分配透视值而不必像201701,201702,201703那样单独写每一列......?

1 个答案:

答案 0 :(得分:0)

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period_nk) 
            FROM temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT category, ' + @cols + ' from 
            (
                select  category,
                        period_nk,
                        amount
                from temp
           ) x
            pivot 
            (
                 max(amount)
                for period_nk in (' + @cols + ')
            ) p '


execute(@query)

drop table temp

输出:

 category   201701  201702  201703  201704  201705
1   ABC 1000,0000   NULL    NULL    NULL    1100,0000
2   DEF NULL    500,0000    NULL    700,0000    NULL
3   GHI NULL    NULL    800,0000    NULL    NULL

online demo