0

重複の可能性:
これら2つのSQLステートメントを組み合わせる方法は?

2つのSQLクエリがあります。CMSUIDそれらは、変数がテーブルのいずれかまたは値に等しいことに基づいてカウントを取得CASUIDします。それ以外はまったく同じです。CASEおそらくステートメントを使用して、それらを1つのクエリに組み合わせるにはどうすればよいですか。

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の仕組みをご覧ください。

基本的に、一方の列で1つのカウントを選択し、次に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 に答える