派生表的多次计数

时间:2016-06-14 11:53:41

标签: sql-server derived-table

我试图通过使用派生表计算总入围名单和总感兴趣,但它无效。

select  (SELECT COUNT(ID) FROM Dtable WHERE Is_shortlisted=1) AS TOTALSHORLISTED,           
        (SELECT COUNT(ID) FROM Dtable WHERE Is_Interested=1) AS TOTALINERESTED 
from (
        SELECT  BM.ID,
                BM.Is_Interested,
                BM.Is_shortlisted,
                BM.Business_Masla_Status_ID
        FROM  Business_Maslahal BM
        INNER join Vw_MaslaInfo MI 
            on BM.[MaslaHal_ID]=MI.ID and BM.ID=2 AND MI.Masla_status_ID IN(1,2) 
) Dtable

2 个答案:

答案 0 :(得分:3)

实际上,您甚至不需要派生表:

SELECT  SUM(CASE WHEN Is_shortlisted=1 THEN 1 ELSE 0 END) AS TOTALSHORLISTED,
        SUM(CASE WHEN Is_Interested=1 THEN 1 ELSE 0 END) AS TOTALINERESTED 
FROM  Business_Maslahal BM
INNER join Vw_MaslaInfo MI 
ON BM.[MaslaHal_ID]=MI.ID 
WHERE and BM.ID=2 
AND MI.Masla_status_ID IN(1,2)

我还将一些条件从ON子句移到了WHERE子句。它应该对结果没有影响,但它使查询更具可读性。

答案 1 :(得分:2)

尝试这种方式:

select  SUM(CASE WHEN Is_shortlisted=1 THEN 1 ELSE 0 END) AS TOTALSHORLISTED,
        SUM(CASE WHEN Is_Interested=1 THEN 1 ELSE 0 END) AS TOTALINERESTED 
from (
    SELECT  BM.ID,
            BM.Is_Interested,
            BM.Is_shortlisted,
            BM.Business_Masla_Status_ID
    FROM  Business_Maslahal BM
    INNER join Vw_MaslaInfo MI 
        on BM.[MaslaHal_ID]=MI.ID and BM.ID=2 AND MI.Masla_status_ID IN(1,2) 
) Dtable