0

可能重复:
如何组合这两个 SQL 语句?

我有 2 个 SQL 查询。他们根据变量等于CMSUIDCASUID表中的值来获得计数。否则,它们完全相同。我怎样才能将它们组合成一个查询,也许使用一个CASE语句。

select @cntCM_CNF = count(distinct(c.ID_Case))
from dbo.Cases c
join dbo.vew_CasePersonnelSystemIDs vcps on c.ID_Case = vcps.ID_Case
join hearings h on c.ID_Case = h.ID_Case
where vcps.CMSUID = @nSUID
    and h.HearingDate > getdate()
    and h.OnCalendar = 1 and h.Scheduled = 1
    and dbo.fn_HearingConfirmedNoHOs(h.ID_Hearing) < 2

select @cntCC_CNF = count(distinct(c.ID_Case))
from dbo.Cases c
join dbo.vew_CasePersonnelSystemIDs vcps on c.ID_Case = vcps.ID_Case
join hearings h on c.ID_Case = h.ID_Case
where vcps.CASUID = @nSUID
    and h.HearingDate > getdate()
    and h.OnCalendar = 1 and h.Scheduled = 1
    and dbo.fn_HearingConfirmedNoHOs(h.ID_Hearing) < 2  

我不知道如何组合它们,因为结果是不同项目的计数。不知道如何做到这一点。

4

2 回答 2

2

是吗...

select 
    @cntCM_CNF = count(distinct case when vcps.CMSUID = @nSUID then c.ID_Case else null end),
    @cntCC_CNF = count(distinct case when vcps.CASUID = @nSUID then c.ID_Case else null end)
from dbo.Cases c
join dbo.vew_CasePersonnelSystemIDs vcps on c.ID_Case = vcps.ID_Case
join hearings h on c.ID_Case = h.ID_Case
where 
    h.HearingDate > getdate()
    and h.OnCalendar = 1 and h.Scheduled = 1
    and dbo.fn_HearingConfirmedNoHOs(h.ID_Hearing) < 2 AND
    (vcps.CASUID = @nSUID OR vcps.CMSUID = @nSUID) --<<<<added for performance reasons
于 2012-12-30T23:05:35.620 回答
1

看看 UNION 是如何工作的。

本质上,您将在一列中选择一个计数,0,然后在另一列中选择 0。

你可能需要使用UNION ALL

select @cntCM_CNF = count(distinct(c.ID_Case)) AS Col1, 0 As Col2
from dbo.Cases c
join dbo.vew_CasePersonnelSystemIDs vcps on c.ID_Case = vcps.ID_Case
join hearings h on c.ID_Case = h.ID_Case
where vcps.CMSUID = @nSUID
    and h.HearingDate > getdate()
    and h.OnCalendar = 1 and h.Scheduled = 1
    and dbo.fn_HearingConfirmedNoHOs(h.ID_Hearing) < 2
UNION ALL
select 0 as Col1, @cntCC_CNF = count(distinct(c.ID_Case)) AS Col2
from dbo.Cases c
join dbo.vew_CasePersonnelSystemIDs vcps on c.ID_Case = vcps.ID_Case
join hearings h on c.ID_Case = h.ID_Case
where vcps.CASUID = @nSUID
    and h.HearingDate > getdate()
    and h.OnCalendar = 1 and h.Scheduled = 1
    and dbo.fn_HearingConfirmedNoHOs(h.ID_Hearing) < 2  
于 2012-12-30T22:18:58.620 回答