SQL - 2在一个查询中计数

时间:2010-12-02 12:09:05

标签: sql-server tsql count group-by

我有2个查询返回表中不同信息的计数:

SELECT Date, COUNT(*) AS Total 
FROM Table
WHERE Type = 7 AND Date >= '2010-01-01' 
GROUP BY Date 
HAVING COUNT(*) > 5000  
ORDER BY Date

返回所有“忙碌”日期的总计:

Date       Total
---------- -----------
2010-01-05 9466
2010-02-02 8747
2010-03-02 9010
2010-04-06 7916
2010-05-05 9342
2010-06-02 8723
2010-07-02 7829
2010-08-03 8411
2010-09-02 7687
2010-10-04 7706
2010-11-02 8567
2010-12-02 7645

SELECT Date, COUNT(*) AS Failures
FROM Table
WHERE Type = 7 AND ErrorCode = -2 AND Date >= '2010-01-01' 
GROUP BY Date 
ORDER BY Date

返回总失败(所有这些都发生在繁忙的日期):

Date       Failures
---------- -----------
2010-09-02 29
2010-10-04 16
2010-11-02 8

是否可以将这些组合成一个查询以返回一个结果?

E.g:

Date       Total       Failures
---------- ----------- -----------
2010-01-05 9466
2010-02-02 8747
2010-03-02 9010
2010-04-06 7916
2010-05-05 9342
2010-06-02 8723
2010-07-02 7829
2010-08-03 8411
2010-09-02 7687         29
2010-10-04 7706         16
2010-11-02 8567         8
2010-12-02 7645

3 个答案:

答案 0 :(得分:9)

;With baseData As
(
SELECT 
      Date, 
      COUNT(*) AS Total, 
      COUNT(CASE WHEN ErrorCode = -2 THEN 1 END)  AS Failures
FROM Table
WHERE Type = 7 AND Date >= '2010-01-01' 
GROUP BY Date 
)
SELECT 
     Date,
     Total,
     Failures, 
     CAST(Failures AS float)/Total AS Ratio
FROM baseData
WHERE Total > 5000  OR Failures > 0
ORDER BY Date

答案 1 :(得分:2)

如果你可以重构相同的where子句,那么这应该是可能的。

我没有考虑你的HAVING(Count())

SELECT [Date], COUNT(*) AS Total, SUM(CASE WHEN ErrorCode = -2 THEN 1 ELSE 0 END) AS Failures 
FROM [Table]
WHERE [Type] = 7  AND [Date] >= '2010-01-01'  
GROUP BY [Date]  
ORDER BY [Date] 

编辑:这是一些测试数据

create table [Table]
(
[ErrorCode] int,
[Type] int,
[Date] datetime
)

insert into [table]([Date], [Type], [ErrorCode] )values ('1 Jan 2010', 7, 0)
insert into [table]([Date], [Type], [ErrorCode] )values ('1 Jan 2010', 7, -2)
insert into [table]([Date], [Type], [ErrorCode] )values ('2 Jan 2010', 7, -2)
insert into [table]([Date], [Type], [ErrorCode] )values ('2 Jan 2010', 8, -2)
insert into [table]([Date], [Type], [ErrorCode] )values ('2 Jan 2010', 7, 1)

答案 2 :(得分:0)

是的,您应该可以在2个表之间进行UNION ALL