通过sql从group with fi count 0行计数

时间:2018-01-10 09:52:09

标签: sql sql-server

我有一个select查询来选择一个ID和相应的计数,并根据ID对它们进行分组,这是那个的

SELECT  InID, 
        COUNT(*) as ICount       
FROM RawData
WHERE CompletedDate>= @BeginDate  AND CompletedDate<= @EndDate  
AND  InID in (3851,4151,11)
GROUP BY InID

这只为我返回一条记录

4151   225

为了找到缺失的条目,即3851和11,我尝试了查询

SELECT InID, 
       COUNT(*) as ICount 
FROM RawData
WHERE CompletedDate>= @BeginDate  AND CompletedDate<= @EndDate  
AND InID in (3851,4151,11)
GROUP BY InID
HAVING COUNT(*)=0

但是它返回了0条记录。因此,通过正确的方式检查组中缺少记录的ID

4 个答案:

答案 0 :(得分:1)

试试这个:我认为您可以通过OUTER APPLY获得所需的输出,如下所示:

SELECT InID, rd1.ICount      
FROM RawData rd
OUTER APPLY (SELECT COUNT(*) ICount 
            FROM RowDate rd1 
            WHERE rd1.InID = rd.InID 
            AND rd1.CompletedDate>= @BeginDate  
            AND rd1.CompletedDate<= @EndDate) rd1  
WHERE InID IN (3851,4151,11)
GROUP BY InID

没有记录的ID将显示NULL

答案 1 :(得分:1)

使用LEFT JOIN

SELECT r.InID, ISNULL(c.ICount, 0) as ICount
FROM RawData r
    LEFT JOIN (
        select InID, COUNT(*) as ICount 
        FROM RawData
        where CompletedDate>= @BeginDate  AND CompletedDate<= @EndDate  
            and InID in (3851,4151,11)
        group by InID
    ) c ON c.InID = r.InID
WHERE r.InID in (3851,4151,11)

使用OUTER APPLY

SELECT r.InID, ISNULL(c.ICount, 0) as ICount
FROM RawData r
    OUTER APPLY (
        select COUNT(*) as ICount 
        FROM RawData
        where CompletedDate>= @BeginDate  AND CompletedDate<= @EndDate  
            and InID = r.InID
    ) c 
WHERE r.InID in (3851,4151,11)

答案 2 :(得分:1)

如果没有指定Id的记录,那么这不会给你返回一行满足Where子句中的条件。你可以试试这个逻辑

;WITH CTE
AS
(
    SELECT MyId = 3851
    UNION ALL
    SELECT 4151
    UNION ALL
    SELECT 11
)
SELECT
    CTE.MyId,
    COUNT(1)
    FROM CTE
        LEFT JOIN RawData RD
            ON CTE.MyId = RD.InID
        WHERE CompletedDate>= @BeginDate  
            AND CompletedDate<= @EndDate 
        GROUP BY CTE.MyId

或者简单地说这也适合你

select 
    InID, 
    SUM(CASE WHEN CompletedDate>= @BeginDate  
AND CompletedDate<= @EndDate  THEN 1 ELSE 0 END) as ICount 
    FROM RawData
        whereInID in (3851,4151,11)
        group by InID

过滤零计数的记录

select 
        InID, 
        SUM(CASE WHEN CompletedDate>= @BeginDate  
    AND CompletedDate<= @EndDate  THEN 1 ELSE 0 END) as ICount 
        FROM RawData
            whereInID in (3851,4151,11)
            group by InID
having SUM(CASE WHEN CompletedDate>= @BeginDate  
    AND CompletedDate<= @EndDate  THEN 1 ELSE 0 END) = 0

答案 3 :(得分:0)

您需要从包含要包含的所有值的结果集执行左连接

select ids.Id, count(InId)
from 
(select 3851 as Id union select 4151 union select 11) ids
left join
    RawData
on ids.id = rawdata.inid
where CompletedDate>= @BeginDate  AND CompletedDate<= @EndDate  
group by Ids.id