2

我想构建一个 SQL 查询,它将消除重复值DISTINCT,然后Sum将列值打印为标题并获得结果

样本数据 :-

ID  TYPE    Values
A   FLM     00:34:09
A   FLM     16:03:19
A   SLM     00:37:48
B   FLM     00:42:47
B   SLM     01:14:56
C   SLM     01:00:52
C   SLM     00:37:48

我想为每个然后根据显示做Sum of Values同样的事情TYPEIDType

预期输出:

ID  FLM         SLM
A   16:37:28    00:37:48
B   00:42:47    01:14:56
C   NULL        01:38:40

我得到了什么

ID  FLM         SLM
A   01:38:40    NULL
A   NULL        00:37:48
B   00:42:47    NULL
B   NULL        01:14:56
C   NULL        01:38:40

在这里,我可以对每种类型进行求和,但结果显示在两个不同的行而不是单行中。

我的查询:

Select Distinct ID
    CASE 
        When Type='SLM' 
        Then    STR(SUM(DateDiff(s,[Start Date],[End Date]))/3600) + 
                RIGHT(CONVERT(char(8),DATEADD(s,SUM(DateDiff(s,[Start Date],[End Date])),0),108),6)
    End[FLM],
    CASE    
        When Type='SLM' 
        Then    STR(SUM(DateDiff(s,[Start Date],[End Date]))/3600) + 
                RIGHT(CONVERT(char(8),DATEADD(s,SUM(DateDiff(s,[Start Date],[End Date])),0),108),6)
    End[SLM],

From #_TicketType GROUP BY ID,Type

PS 使用[Start Date],[End Date]数据类型的列DateTimeValues在示例数据表中得到列。

4

2 回答 2

4

(已更新)Type从您的中删除group by,并将 CASE 移动到 SUM 中,如下所示:

Select ID,
    STR(SUM(CASE Type WHEN 'FLM' THEN DateDiff(s,[Start Date],[End Date]) END)/3600) +
    RIGHT(CONVERT(char(8),DATEADD(s,SUM(CASE Type WHEN 'FLM' THEN DateDiff(s,[Start Date],[End Date]) END),0),108),6) [FLM],
    STR(SUM(CASE Type WHEN 'SLM' THEN DateDiff(s,[Start Date],[End Date]) END)/3600) +
    RIGHT(CONVERT(char(8),DATEADD(s,SUM(CASE Type WHEN 'SLM' THEN DateDiff(s,[Start Date],[End Date]) END),0),108),6) [SLM]
From #_TicketType 
GROUP BY ID
于 2013-04-13T09:48:48.650 回答
1

对整个 CASE 表达式使用 SUM() 函数

SELECT ID,
    STR(SUM(CASE WHEN Type = 'FLM' 
                 THEN DATEDIFF(s,[Start Date],[End Date]) 
            END) /3600) +
    RIGHT(CONVERT(char(8),DATEADD(s, SUM(CASE WHEN Type = 'FLM' 
                                   THEN DATEDIFF(s,[Start Date],[End Date]) END),0)
                              ,108),6) AS [FLM],                                  
    STR(SUM(CASE WHEN Type = 'SLM' 
                 THEN DATEDIFF(s,[Start Date],[End Date])
            END)) /3600 + 
    RIGHT(CONVERT(char(8),DATEADD(s, SUM(CASE WHEN Type = 'SLM' 
                                   THEN DATEDIFF(s,[Start Date],[End Date]) END),0)
                              ,108),6) AS [SLM]
FROM #_TicketType 
GROUP BY ID
于 2013-04-13T10:10:34.640 回答