2012-12-30 154 views
2

我有2個SQL查詢都獲得不同ID的計數。如何結合這兩個SQL語句?

select @cntCM_CMQ = count(*) 
from dbo.CaseWorkflow cw 
join vew_CasePersonnelSystemIDs vcps on cw.ID_Case = vcps.ID_Case 
join dbo.WorkflowStates ws on ws.ID_WorkflowState = cw.ID_WorkflowState 
where CMSUID = @nSUID and ws.ID_WorkflowType = 3 -- CMQ 

select @cntCM_PRWK = count(*) 
from dbo.CaseWorkflow cw 
join vew_CasePersonnelSystemIDs vcps on cw.ID_Case = vcps.ID_Case 
join dbo.WorkflowStates ws on ws.ID_WorkflowState = cw.ID_WorkflowState 
where CMSUID = @nSUID and ws.ID_WorkflowType = 1 -- PAPERWORK 

看來,我應該能夠將它們組合成一個單一的選擇(或許還有一個CASE語句),但我似乎無法破解它。

回答

6

像這樣的事情被忽略?

select sum(case when ws.ID_WorkflowType = 1 then 1 else 0 end) as cntCM_PRWK 
    , sum(case when ws.ID_WorkflowType = 3 then 1 else 0 end) as cntCM_CMQ 
from dbo.CaseWorkflow cw 
join vew_CasePersonnelSystemIDs vcps on cw.ID_Case = vcps.ID_Case 
join dbo.WorkflowStates ws on ws.ID_WorkflowState = cw.ID_WorkflowState 
where CMSUID = @nSUID 
3
select 
    @cntCM_CMQ = count(case when ws.ID_WorkflowType = 3 then ws.ID_WorkflowType end) 
    , @cntCM_PRWK = count(case when ws.ID_WorkflowType = 1 then ws.ID_WorkflowType end) 
from 
    dbo.CaseWorkflow cw 
    join vew_CasePersonnelSystemIDs vcps on cw.ID_Case = vcps.ID_Case 
    join dbo.WorkflowStates ws on ws.ID_WorkflowState = cw.ID_WorkflowState 
where 
    CMSUID = @nSUID 
    and ws.ID_WorkflowType in (1, 3) 
3

這樣做有一個竅門。基本上你使用Case爲你感興趣的行挑選一個1值,然後Sum獲得一個數。案例默認爲null如果沒有匹配的情況下,其得到由Sum

Select 
    @cntCM_CMQ = Sum(Case ws.ID_WorkflowType When 3 Then 1 End), 
    @cntCM_PRWK = Sum(Case ws.ID_WorkflowType When 1 Then 1 End) 
From 
    dbo.CaseWorkflow cw 
    inner join 
    vew_CasePersonnelSystemIDs vcps 
    on cw.ID_Case = vcps.ID_Case 
    inner join 
    dbo.WorkflowStates ws 
    on ws.ID_WorkflowState = cw.ID_WorkflowState 
Where 
    CMSUID = @nSUID 
4
select 
SUM(Cast(Case when ws.ID_WorkflowType = 3 then 1 else 0 end as int) as CMQ 
,SUM(Cast(Case when ws.ID_WorkflowType = 1 then 1 else 0 end as int) as Paperwork 

from dbo.CaseWorkflow cw 
join vew_CasePersonnelSystemIDs vcps on cw.ID_Case = vcps.ID_Case 
join dbo.WorkflowStates ws on ws.ID_WorkflowState = cw.ID_WorkflowState 
where CMSUID = @nSUID 
1

另一種是類似於其他職位。

鮑勃·杜爾斯的帖子可能是最具可讀性的。

SELECT 
    [cntCM_PRWK] = COUNT(CASE WHEN ws.ID_WorkflowType = 1 THEN ws.ID_WorkflowState ELSE NULL END), 
    [cntCM_CMQ]  = COUNT(CASE WHEN ws.ID_WorkflowType = 3 THEN ws.ID_WorkflowState ELSE NULL END) 
FROM 
    dbo.CaseWorkflow cw 
    INNER JOIN vew_CasePersonnelSystemIDs vcps 
      ON cw.ID_Case = vcps.ID_Case 
    INNER JOIN dbo.WorkflowStates ws 
      ON ws.ID_WorkflowState = cw.ID_WorkflowState 
WHERE CMSUID = @nSUID