我有两个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
语句),但我似乎无法破解它。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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 :(得分: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 :(得分: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