每个人的总数

时间:2017-04-12 06:18:30

标签: sql sql-server select count

我的SQL Server查询有问题。

我的查询必须显示每个类别的总数。不是所有类别的总金额。

SELECT [CATEGORY],
       (SELECT COUNT(*)  
        FROM [Group_New_DB].[dbo].[INCIDENTSM1] 
        WHERE ([OPEN_TIME] >=  @StartDate and [OPEN_TIME] < @EndDate + 1) ) AS OpenedCount, 
       (SELECT COUNT(*)  
        FROM [Group_New_DB].[dbo].[INCIDENTSM1]
        WHERE ([CLOSE_TIME] >=  @StartDate and [CLOSE_TIME] < @EndDate + 1)) AS ClosedCount   
FROM [Group_New_DB].[dbo].[INCIDENTSM1] 
GROUP BY CATEGORY 
ORDER BY CATEGORY

该报告包含一个包含3列的表:类别,已注册,已关闭 1列是类别名称 2列是已注册的类别数 3列 - &gt;关闭了多少列 但结果

结果看起来不合适。

enter image description here

2 个答案:

答案 0 :(得分:1)

我不太明白总数与总金额之间的区别是什么,因为问题没有提供任何背景。

虽然,如果您在命名列时尝试获取OpenedCount和ClosedCount,我建议您尝试下面的步骤:

SELECT
    CATEGORY,
    SUM(CASE WHEN (OPEN_TIME >= @start_date AND OPEN_TIME < @end_date+1) 
        THEN 1 
        ELSE 0
    END) AS OPENED_COUNT,
    SUM(CASE WHEN (CLOSED_TIME >= @start_date AND CLOSED_TIME < @end_date+1) 
        THEN 1 
        ELSE 0
    END) AS CLOSED_COUNT
FROM
    [Group_New_DB].[dbo].[INCIDENTSM1]
GROUP BY
    CATEGORY
ORDER BY
    CATEGORY

IMO,这也是一种更好的方式,因为它不包含多个子查询。

更正:按照TriV的建议将COUNT更改为SUM - 谢谢!

答案 1 :(得分:0)

试试这个 -

SELECT [CATEGORY],
COUNT(CASE WHEN [OPEN_TIME] >=  @StartDate and [OPEN_TIME] < @EndDate + 1 THEN 1 ELSE NULL END) AS OpenedCount, 
COUNT(CASE WHEN [CLOSE_TIME] >=  @StartDate and [CLOSE_TIME] < @EndDate + 1 THEN 1 ELSE NULL END) AS ClosedCount   
FROM [Group_New_DB].[dbo].[INCIDENTSM1] GROUP BY
CATEGORY ORDER BY CATEGORY