我想构建一个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
执行相同TYPE
的{{1}},然后根据ID
显示
预期产出:
Type
我得到的是什么
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
P.S。使用数据类型为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
的列[Start Date],[End Date]
我在示例数据表中获得了列DateTime
。
答案 0 :(得分:4)
(已更新)从Type
中删除group by
,然后在SUM中移动CASE,如下所示:
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
答案 1 :(得分: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