如何在dyamnmic Pivot中使用MAX作为多个值

时间:2017-07-10 08:25:36

标签: sql sql-server tsql

我有一个查询,当我使用静态动态数据透视工作正常

静态脚本

Select Name, tableName,MAX([2017-07-10])[2017-07-10],MAX([2017-07-09])[2017-07-09]
        from (
SELECT      Target_Db_Name,
            Target_Tbl_Name,
            Cnt
    FROM Table1 l 

            WHERE Name='Employee' AND
                     dt >= CAST(dateadd(day, -1, getdate()) as date))T
PIVOT (MAX(cnt)FOR dt IN ([2017-07-10],[2017-07-09]) )PVT
GROUP BY  Name, tableName

当我尝试在同一个查询中实现动态查询时,我很困惑,以获取多个逗号分隔数据值的最大值

动态脚本

DECLARE @cols  AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';

SELECT @cols = @cols + QUOTENAME(dt) + ',' FROM (select distinct CONVERT(DATE,t)Start_dt from Events
WHERE Start_dt >= CAST(dateadd(day, -1, getdate()) as date) ) as tmp ORDER BY Start_dt desc
select @cols = substring(@cols, 0, len(@cols)) 


Select @query = '

Select Name, tableName,'+@cols+'
        from (
SELECT      Name,
            tableName,
            Cnt
    FROM  Table1 l 

            WHERE Name=''Employee'' AND
                     Start_dt >= CAST(dateadd(day, -1, getdate()) as date))T
PIVOT (MAX(Cnt)FOR Start_dt IN ('+@cols+') )PVT
GROUP BY  Name, tableName
'

EXEC   (@query)

所以这里的日期值就像这样

动态如何申请

([2017-07-10]),([2017-07-09])

MAX([2017年7月10日]),MAX([2017年7月9日])

如何在Dynamic Pivot中获取每个日期的最大值

1 个答案:

答案 0 :(得分:0)

以下是在列表

中获取Max聚合的一种方法
SET @cols = stuff((SELECT DISTINCT ','+Quotename(CONVERT(DATE, Start_dt)) 
             FROM   Events
             WHERE  Start_dt >= Cast(Dateadd(day, -1, Getdate()) AS DATE)
             ORDER  BY Start_dt DESC
             FOR xml path('')) ,1,1,'')
--Print @cols

SET @select_cols = stuff((SELECT DISTINCT ',Max('+Quotename(CONVERT(DATE, Start_dt))+') as '+Quotename(CONVERT(DATE, t)) 
             FROM   Events
             WHERE  Start_dt >= Cast(Dateadd(day, -1, Getdate()) AS DATE)
             ORDER  BY Start_dt DESC
             FOR xml path('')) ,1,1,'')
--Print @select_cols

Select @query = '

Select Name, tableName,'+@select_cols+'
        from (
SELECT      Name,
            tableName,
            Cnt
    FROM  Table1 l 

            WHERE Name=''Employee'' AND
                     Start_dt >= CAST(dateadd(day, -1, getdate()) as date))T
PIVOT (MAX(Cnt)FOR Start_dt IN ('+@cols+') )PVT
GROUP BY  Name, tableName
'

EXEC   (@query)

注意:您当前将行转换为csv的方法无法保证始终有效。我用xml path()方法做同样的事情