2

我有 2 个 SQL 查询,它们都获取不同 ID 的计数。

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语句),但我似乎无法破解它。

4

5 回答 5

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
于 2012-12-30T20:28:25.280 回答
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 
于 2012-12-30T20:29:03.453 回答
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)
于 2012-12-30T20:27:01.110 回答
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
于 2012-12-30T20:27:22.880 回答
1

与其他帖子类似的替代方案。

Bob Duells 的帖子可能是最具可读性的。

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
于 2012-12-30T20:53:16.023 回答