选择语句中的计数查询

时间:2018-11-07 00:13:42

标签: sql sql-server

我可以问一个人,为什么下面的两个查询使用MSSMS不会输出相同的结果?我必须在第二个输出中添加些什么,才能获得第一个输出。

|----------------------------------------|
|                 RoomBase               |
|---------------------|------------------|
|     CustomBit1      |       Date       |
|          1          |     2018-11-01   |
|          1          |     2018-11-01   |
|          1          |     2018-11-01   |
|          1          |     2018-11-01   |
|          1          |     2018-11-01   | 
|          1          |     2018-10-01   |
|          0          |     2018-10-01   |
|          0          |     2018-10-01   |
|          0          |     2018-10-01   |
|          1          |     2018-10-01   |
|---------------------|------------------| 

第一个查询的结果。 [所需结果。]

|---------------------|
|        Count        |
|---------------------|
|          2          |
|          5          |
|---------------------|

第二个查询的结果。 [不良结果。]

|---------------------|
|        Count        |
|---------------------|
|         630         |
|         630         |
|---------------------|

630来自原始数据量。

  SELECT ISnull(Count(1),0) FROM dbo.[RoomBase] 
  WHERE dbo.[RoomBase].CustomBit1 = 1 
  GROUP BY [RoomBase].Date



  SELECT (SELECT ISnull(Count(1), 0) FROM dbo.[RoomBase] 
           WHERE dbo.[RoomBase].CustomBit1  =1)
  FROM dbo.[RoomBase]
  GROUP BY [RoomBase].Date

感谢所有帮助...

谢谢!

2 个答案:

答案 0 :(得分:1)

您还应该按日期过滤子查询

SELECT (
    SELECT ISnull(Count(1), 0) FROM dbo.[RoomBase] RB WHERE RB.CustomBit1  = 1
        AND RB.Date = [RoomBase].Date
    )
  FROM dbo.[RoomBase]
  GROUP BY [RoomBase].Date

答案 1 :(得分:0)

“第一查询”将按CustomBit1 = 1分组后对所有具有Date的记录进行计数。

第二个记录将计算所有具有CustomBit1 = 1的记录(不对它们进行分组),因为您没有在子查询中包括该组。

因此,您必须在第二个查询中执行以下操作:

 SELECT 
    (
        SELECT TOP 1
            COUNT(*)
        FROM RoomBase
        WHERE 
            CustomBit1 = 1 
        GROUP BY [Date]
    )
FROM RoomBase

此外,ISNULL()COUNT()函数不需要SUM()。由于这些函数将始终返回整数,而永远不会返回NULL

相关问题