是否可以将这两个查询合并为一个查询
SELECT COUNT(IMA.FKRiskID) AS RiskCountWithoutPlan
FROM Rpt_ImpactAssessment IMA
WHERE IMA.FKItemID = 38
AND IMA.ImpactCurPIDLevel LIKE '%High%'
AND NOT EXISTS
(
select 1
from RM_LinkActionToPlan LAP
where IMA.FKPlanID = LAP.PlanID
)
SELECT COUNT(IMA.FKRiskID) AS RiskCountWithPlan
FROM Rpt_ImpactAssessment IMA
WHERE IMA.FKItemID = 38
AND IMA.ImpactCurPIDLevel LIKE '%High%'
AND EXISTS (
select 1
from RM_LinkActionToPlan LAP
where IMA.FKPlanID = LAP.PlanID
)
答案 0 :(得分:0)
试试这个。它对我使用虚拟数据(我将查询作为注释发布)。这将为您提供两列:第一列是RiskCountWithoutPlan,第二列是RiskCountWithPlan
SELECT
SUM([rcwop]) [RiskCountWithoutPlan],
SUM([rcwp]) [RiskCountWithPlan]
FROM
(
SELECT
CASE WHEN LAP.PlanID IS NULL THEN 1 ELSE 0 END [rcwop],
CASE WHEN LAP.PlanID IS NOT NULL THEN 1 ELSE 0 END [rcwp]
FROM
Rpt_ImpactAssessment IMA
LEFT JOIN RM_LinkActionToPlan LAP ON IMA.FKPlanID = LAP.PlanID
WHERE IMA.FKItemID = 38
AND IMA.ImpactCurPIDLevel LIKE '%High%'
) tbl
希望这就是你要找的东西。
斯图
DECLARE @Rpt_ImpactAssessment TABLE (
FKRiskID INT,
FKItemID INT,
FKPlanID INT,
ImpactCurPIDLevel NVARCHAR(20)
)
DECLARE @RM_LinkActionToPlan TABLE (
FKRiskID INT,
FKItemID INT,
PlanID INT,
ImpactCurPIDLevel NVARCHAR(20)
)
INSERT INTO @Rpt_ImpactAssessment VALUES (1, 38, 2, 'High')
INSERT INTO @RM_LinkActionToPlan VALUES (1, 38, 2, 'High')
INSERT INTO @Rpt_ImpactAssessment VALUES (1, 38, 3, 'High')
INSERT INTO @RM_LinkActionToPlan VALUES (1, 38, 3, 'High')
SELECT
SUM([rcwop]) [RiskCountWithoutPlan],
SUM([rcwp]) [RiskCountWithPlan]
FROM
(
SELECT
CASE WHEN LAP.PlanID IS NULL THEN 1 ELSE 0 END [rcwop],
CASE WHEN LAP.PlanID IS NOT NULL THEN 1 ELSE 0 END [rcwp]
FROM
@Rpt_ImpactAssessment IMA
LEFT JOIN @RM_LinkActionToPlan LAP ON IMA.FKPlanID = LAP.PlanID
WHERE IMA.FKItemID = 38
AND IMA.ImpactCurPIDLevel LIKE '%High%'
) tbl