如何从select语句中删除这些共同相关的子查询

时间:2015-07-14 18:25:22

标签: sql sql-server correlated-subquery

这里我只处理一个表,它有一个名为CmpltStscd的属性,对于每个值,我需要输出中的不同列作为聚合函数。

有没有办法摆脱这些子查询?

尝试很多

Select 
      Mg.RsrcId
    , Count(Mg.ActID) Num_of_Goals
    , (SELECT COUNT(MC.ActID) FROM TM.MatrixGoal MC where MC.CmpltStsCd = 2 AND MG.RsrcID = MC.RsrcID AND MC.ActiveFlg = 1 AND MC.DelFlg = 0 AND MC.CorporateGoalFlg <> 1 AND MC.StsCd in (3,4)) as Complete
    , (SELECT COUNT(MI.ActID) FROM TM.MatrixGoal MI where MI.CmpltStsCd = 4 AND MG.RsrcID = MI.RsrcID AND MI.ActiveFlg = 1 AND MI.DelFlg = 0 AND MI.CorporateGoalFlg <> 1 AND MI.StsCd in (3,4)) as Issues
    , (SELECT COUNT(MO.ActID) FROM TM.MatrixGoal MO where MO.CmpltStsCd = 1 AND MG.RsrcID = MO.RsrcID AND MO.ActiveFlg = 1 AND MO.DelFlg = 0 AND MO.CorporateGoalFlg <> 1 AND MO.StsCd in (3,4)) as OnTrack
From 
TM.MatrixGoal AS Mg

Where MG.ActiveFlg = 1
            AND MG.DelFlg = 0
            AND MG.CorporateGoalFlg <> 1
            AND MG.StsCd in (3,4)
Group By RsrcId

2 个答案:

答案 0 :(得分:3)

您需要透视/交叉标签查询

SELECT Mg.RsrcId,
       COUNT(Mg.ActID) Num_of_Goals,
       SUM(CASE
             WHEN CmpltStsCd = 2 THEN 1
             ELSE 0
           END)        AS Complete,
       SUM(CASE
             WHEN CmpltStsCd = 4 THEN 1
             ELSE 0
           END)        AS Issues,
       SUM(CASE
             WHEN CmpltStsCd = 1 THEN 1
             ELSE 0
           END)        AS OnTrack
FROM   TM.MatrixGoal AS Mg
WHERE  MG.ActiveFlg = 1
       AND MG.DelFlg = 0
       AND MG.CorporateGoalFlg <> 1
       AND MG.StsCd IN ( 3, 4 )
GROUP  BY RsrcId 

答案 1 :(得分:1)

我认为你可以使用条件聚合:

Select Mg.RsrcId, Count(Mg.ActID) Num_of_Goals,
       SUM(CASE WHEN mg.CmpltStsCd = 2 THEN 1 ELSE 0 END) as Complete,
       SUM(CASE WHEN mg.CmpltStsCd = 4 THEN 1 ELSE 0 END) as Issues
       SUM(CASE WHEN mg.CmpltStsCd = 1 THEN 1 ELSE 0 END) as OnTrack
From TM.MatrixGoal Mg
Where MG.ActiveFlg = 1 AND MG.DelFlg = 0 AND MG.CorporateGoalFlg <> 1 AND 
     MG.StsCd in (3,4)
Group By RsrcId;