如何将这两个SELECT组合成一个?

时间:2012-12-30 22:14:53

标签: sql sql-server sql-server-2005

  

可能重复:
  How to combine these two SQL statements?

我有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  

我无法弄清楚如何组合它们,因为结果是不同项目的数量。不知道如何实现这一目标。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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  
相关问题