我有以下表结构
TicketID Status Duration
-----------------------------
1234 8 2
1233 8 10
1232 4 5
1231 8 12
1230 4 50
需要以下列方式输出。请只做那些需要的。如果可能的话,我想在单个SQL查询中使用它。
请帮我按以下方式输出。
Status Closed (sum) Open(Sum)
---------------------------------
8 24 0
4 0 55
答案 0 :(得分:0)
case
表达式可以过滤掉不需要的值,因此可以在单个聚合查询中完成:
SELECT status,
SUM (CASE status WHEN 8 THEN duration ELSE 0 END) AS closed_sum,
SUM (CASE status WHEN 4 THEN duration ELSE 0 END) AS open_sum
FROM my_table
GROUP BY status
答案 1 :(得分:0)
select status
, sum( case when status = 4 then Duration else 0 end ) as [Open(sum)]
, sum( case when status = 8 then Duration else 0 end ) as [Closed(sum)]
from @test
group by status
order by status desc
答案 2 :(得分:0)
WITH T AS (SELECT Status, SUM(Duration) AS Duration FROM Table1 GROUP BY Status)
SELECT Status, Duration, 0 FROM T WHERE Status = 8
UNION ALL
SELECT Status, 0, Duration FROM T WHERE Status = 4
答案 3 :(得分:0)
使用union all
SELECT [Status],sum([Duration]) [Closed(sum)], '0' as [Open(Sum)]
from [dbo].[tblx]
where [Status]=8
GROUP BY [Status]
UNION all
SELECT [Status], '0' as [Closed(sum)],sum([Duration]) [Close(sum)]
from [dbo].[tblx]
WHERE [Status]=4
GROUP BY [Status]