我有三个SELECT语句,每个语句都返回一个总数,'New Cases','Closes Cases','Existing Cases'。如何组合它们以便在一个结果集中返回它们。
即我需要一张带有3个字段的表格,“新案例”,“关闭案例”和“现有案例”各有一个
SELECT COUNT(CaseID) AS 'New Cases'
FROM dbo.ClientCase
WHERE (CaseStartDate >= CONVERT(DATETIME, '2009-01-01 00:00:00', 102))
AND (CaseStartDate <= CONVERT(DATETIME, '2009-03-31 00:00:00', 102))
SELECT COUNT(CaseID) AS 'Closed Cases'
FROM dbo.ClientCase
WHERE (CaseClosedDate >= CONVERT(DATETIME, '2009-01-01 00:00:00', 102))
AND (CaseClosedDate <= CONVERT(DATETIME, '2009-03-31 00:00:00', 102))
SELECT COUNT(CaseID) AS 'Existing Cases'
FROM dbo.ClientCase
WHERE (CaseStartDate <= CONVERT(DATETIME, '2009-03-31 00:00:00', 102))
答案 0 :(得分:13)
在计算相同数据时,您可以并行执行:
select
sum(case when CaseStartDate between '2009-01-01' and '2009-03-31' then 1 else 0 end) as [New Cases],
sum(case when CaseClosedDate between '2009-01-01' and '2009-03-31' then 1 else 0 end) as [Closed Cases],
sum(case when CaseStartDate <= '2009-03-31' then 1 else 0 end) as [Existing Cases]
from
dbo.ClientCase
答案 1 :(得分:0)
@Mitch,@ Guffa ..一个很好的解决方案,但为了获得正确的结果,您需要考虑CaseStartDate和CaseClosedDate字段。例如。在New Cases中,如果你不过滤CaseClosedDate数据,你将得不到正确的no。 NewCases,因为它仍将在封闭的情况下计算。
抱歉,我必须将其作为答案发布,因为我没有enuf声誉来添加评论。