MSSQL在子查询或外部应用中计算多个条件?

时间:2016-04-13 14:00:07

标签: sql sql-server join

我的查询目前在字段选择部分中有一些计数。

SELECT userid,
       (SELECT Count(*) AS Expr1
        FROM   dbo.relationships
        WHERE  ( authorised IS NOT NULL
                 AND expired IS NULL
                 AND relationshipended IS NULL )
               AND ( mentorid = u.userid )) AS MenteeCount,
       (SELECT Count(*) AS Expr1
        FROM   dbo.relationships AS Relationships_3
        WHERE  ( authorised IS NULL )
               AND (rejecteddate IS NULL)
               AND (mentorid = u.userid)) AS UnansweredRequests
FROM   users

使用外部应用这样做会更好(更精简),因为我有两个来自同一个外部表的计数吗?

e.g。使用CASE WHEN

2 个答案:

答案 0 :(得分:1)

您不需要使用申请,您只需使用案件的总和:

SELECT
    u.userId,
    MenteeCount = SUM(CASE WHEN  authorised IS NOT NULL AND expired IS NULL AND relationshipended IS NULL THEN 1 ELSE 0 END),
    UnansweredRequests =SUM(CASE WHEN authorised IS NULL AND rejecteddate IS NULL THEN 1 ELSE 0 END)
FROM
   users u
INNER JOIN
   dbo.relationships r
ON  u.userid = mentorid

答案 1 :(得分:0)

是。您应该在一个子查询中进行计算:

SELECT u.userid, r.MenteeCount, r.UnansweredRequests
FROM users u OUTER APPLY
     (SELECT SUM(CASE WHEN authorised IS NOT NULL AND expired IS NULL AND relationshipended IS NULL
                      THEN 1 ELSE 0
                 END) as MenteeCount
             SUM(CASE WHEN authorised IS NULL AND rejecteddate IS NULL
                      THEN 1 ELSE 0
                 END) as UnansweredRequests
      FROM  dbo.relationships r
      WHERE r.mentorid = u.userid
     ) r ;

这样,对每个mentorid只进行一次总结关系表的处理。请注意,在指定关联子句时(对于子查询或apply,您应始终使用完全限定的列名。这有助于避免将来出现问题。