SQL Pivot报告 - 未按要求分组

时间:2016-05-24 01:37:09

标签: sql pivot-table

我有一个返回'pivot'结果SET的查询。我遇到的问题是我需要匹配每个时间戳的参数来自略有不同的时间戳 - 如下图所示。

我需要将5个参数--- gty,tmp,rate,mf,prs ---中的每一个组合成任意“maxtime”下的1行,忽略空值

任何想法??

SELECT [time], Tagname, GTY, TMP, FLOW as Rate, MF, PRS
FROM y
PIVOT
(
       max(lastvalue)
       FOR [tag2] IN (GTY, TMP, FLOW, MF, PRS)
) AS P

SQL Piv

1 个答案:

答案 0 :(得分:1)

将它分组,以便保留时间部分 如果你需要列出逗号分隔的所有唯一值而不是max,那么我有一个CLR聚合函数,如果你使用的是SQL Server,你可以使用它。

SELECT max([time]) AS 'time',
       Tagname,
       max(GTY) AS 'GTY',
       max(TMP) AS 'TMP',
       max(FLOW) AS 'Rate',
       max(MF) AS 'MF',
       max(PRS) AS 'PRS'
FROM y
GROUP BY Tagname

或者通过

将您的数据透视包装在一个组中
SELECT max([time]) AS 'time',
           Tagname,
           max(GTY) AS 'GTY',
           max(TMP) AS 'TMP',
           max(FLOW) AS 'Rate',
           max(MF) AS 'MF',
           max(PRS) AS 'PRS'
    FROM (SELECT [time], Tagname, GTY, TMP, FLOW as Rate, MF, PRS
          FROM y
          PIVOT
          (
          max(lastvalue)
          FOR [tag2] IN (GTY, TMP, FLOW, MF, PRS)
          ) AS P) y
    GROUP BY Tagname

或者更好的是,使用CTE

WITH PIV AS 
(SELECT [time], Tagname, GTY, TMP, FLOW as Rate, MF, PRS
FROM y
PIVOT
(
       max(lastvalue)
       FOR [tag2] IN (GTY, TMP, FLOW, MF, PRS)
) AS P)
SELECT max([time]) AS 'time',
           Tagname,
           max(GTY) AS 'GTY',
           max(TMP) AS 'TMP',
           max(FLOW) AS 'Rate',
           max(MF) AS 'MF',
           max(PRS) AS 'PRS'
    FROM PIV
    GROUP BY Tagname