SQL Query行需要动态转换为列

时间:2016-08-27 10:20:33

标签: sql sql-server pivot

请帮我解决下面的问题 - 我的表中有以下数据 -

npm run sass

我想要像这样的解决方案

Agent   Variable    Chandigarh      NewDelhi
ABC     Leads       102.00          10
ABC     TotalTime   10.52           1
ABC     RPH         22.79           22
ABC     TotalRev    239.70          23
XYZ     Leads       14.00           14
XYZ     TotalTime   1.52            1
XYZ     RPH         21.64           21
XYZ     TotalRev    32.90           32

仅供参考,我可以在列中有更多状态,它没有限制,可能是10或20或5等。所以我需要结果动态查询。请帮帮我,没有静态查询可以吗?

1 个答案:

答案 0 :(得分:0)

动态SQL +透视:

DECLARE @sql nvarchar(max),
        @columns nvarchar(max),
        @col_to_cast nvarchar(max),
        @col_unpvt nvarchar(max)

--This will give:
--,[Chandigarh_Leads],[Chandigarh_RPH]....[NewDelhi_TotalRev],[NewDelhi_TotalTime]

SELECT  @columns = COALESCE(@columns,'')+',['+name+'_'+Variable +']'
FROM (
    SELECT DISTINCT Variable
    FROM #yourtable) v
CROSS JOIN (
    SELECT name
    FROM sys.columns
    WHERE object_id = OBJECT_ID(N'#yourtable')
    AND name not in ('Agent', 'Variable')
    ) c
ORDER BY c.name, v.Variable

--As columns while unpivoting must be same type we need to cast them in same datattype:
--This will give
--,CAST([Chandigarh] as float) as [Chandigarh],CAST([NewDelhi] as float) as [NewDelhi]

SELECT @col_to_cast = COALESCE(@col_to_cast,'')+',CAST(' + QUOTENAME(name)+ ' as float) as '+ QUOTENAME(name)
        @col_unpvt = COALESCE(@col_unpvt,'') + ','+ QUOTENAME(name)
FROM sys.columns
WHERE object_id = OBJECT_ID(N'#yourtable')
AND name not in ('Agent', 'Variable')

SELECT @sql = N'
SELECT *
FROM (
    SELECT  Agent,
            [Columns]+''_''+Variable as ColName,
            [Values] as ColVal
    FROM (
        SELECT  Agent, 
                Variable'+@col_to_cast+'
        FROM #yourtable
        ) p
    UNPIVOT (
        [Values] FOR [Columns] IN ('+STUFF(@col_unpvt,1,1,'')+')
    ) unpvt
) t
PIVOT (
    MAX(ColVal) FOR ColName IN ('+STUFF(@columns,1,1,'')+')
) pvt'

EXEC sp_executesql @sql

输出:

Agent   Chandigarh_Leads    Chandigarh_RPH  Chandigarh_TotalRev Chandigarh_TotalTime    NewDelhi_Leads  NewDelhi_RPH    NewDelhi_TotalRev   NewDelhi_TotalTime
ABC     102                 22,79           239,7               10,52                   10              22              23                  1
XYZ     14                  21,64           32,9                1,52                    14              21              32                  1