如何获取使用子查询返回的列值的计数?

时间:2014-07-09 20:04:41

标签: sql sql-server count subquery aggregate-functions

我想获取STAGING_CUST_ACCT表的acct_key列中不存在的所有hrc_acct_num。最后一个外部选择列抛出错误。如何获取使用子查询返回的列的计数?

SELECT source_sys_cd, 
       Count(CASE 
               WHEN is_delete = 0 THEN 1 
             END) [DEL IS 0], 
       Sum(CASE 
             WHEN trans_amt = 0 THEN 1 
             ELSE 0 
           END)   [STG $0 TXN CNT], 
       Count(CASE 
               WHEN hrc_acct_num NOT IN(SELECT DISTINCT acct_key 
                                        FROM   staging_cust_acct) THEN 
               hrc_acct_num 
             END) 
FROM   staging_transactions (nolock) 
GROUP  BY source_sys_cd 
ORDER  BY source_sys_cd  

2 个答案:

答案 0 :(得分:1)

您可以对子查询执行LEFT JOIN,然后在值为null时执行SUM。 acct_key

SELECT source_sys_cd, 
       Count(CASE 
               WHEN is_delete = 0 THEN 1 
             END) [DEL IS 0], 
       Sum(CASE 
             WHEN trans_amt = 0 THEN 1 
             ELSE 0 
           END)   [STG $0 TXN CNT], 
       SUM(CASE WHEN T.acct_key is NULL THEN 1 else 0  END ) CountNotIN

FROM   staging_transactions (nolock) s
       LEFT JOIN (SELECT DISTINCT acct_key 
                                        FROM   staging_cust_acct) t 
        s.hrc_acct_num  = t.acct_key 
GROUP  BY source_sys_cd 
ORDER  BY source_sys_cd  

Here's a simplified demo

答案 1 :(得分:1)

您可以使用NOT EXISTS将子查询短路。它比LEFT JOIN (SELECT DISTINCT更有效率,因为你不关心枚举它确实存在的所有时间。

   SELECT source_sys_cd, 
           Count(CASE is_delete WHEN 
                   WHEN is_delete = 0 THEN 1 
                 END) [DEL IS 0], 
           Count(CASE 
                   WHEN trans_amt = 0 THEN 1 
                 END) [STG $0 TXN CNT], 
           Count(CASE 
                   WHEN NOT EXISTS (SELECT 1
                                    FROM staging_cust_acct
                                    WHERE acct_key = hrc_acct_num) THEN 1
                 END) 
    FROM   staging_transactions (nolock)
    GROUP  BY source_sys_cd 
    ORDER  BY source_sys_cd