我目前有一个SQL查询,如下所示:
SELECT CONVERT(DECIMAL(5,1),(
CONVERT(DECIMAL(6,1),(
SELECT COUNT(*)
FROM Requests
LEFT JOIN RequestSLA ON Requests.RequestId = RequestSLA.RequestId
WHERE DateLogged between '2015/03/01' and '2015/08/17'
AND RespondBy <= Responded
))/CONVERT(DECIMAL(6,1),(
SELECT COUNT(*)
FROM Requests
WHERE DateLogged between '2015/03/01' and '2015/08/17'
)))
*100)
这将返回在提供的日期范围内违反其响应的SLA(响应在RespondBy之后)的故障单的百分比。是否可以调整此查询以分别显示每天的百分比? I.E.像这样的东西:
Date Percentage
2015-03-01 10
2015-03-02 7
等...
我尝试使用GROUP BY
子句,但这没有用,因为DateLogged(我将分组的)不包含在语句的输出中
答案 0 :(得分:3)
使用单个查询而不是两个相关的子选择,然后您可以使用GROUP BY DateLogged
,您只需要在其中一个计数中放置一个案例表达式:
SELECT r.DateLogged,
Total = COUNT(*),
BreachedSLA = COUNT(CASE WHEN sla.RespondBy <= sla.Responded THEN 1 END),
PercentBreached = CONVERT(DECIMAL(6, 1), 100.0 * COUNT(CASE WHEN sla.RespondBy <= sla.Responded THEN 1 END) / COUNT(*))
FROM Requests AS r
LEFT JOIN RequestSLA AS sla
ON r.RequestId = sla.RequestId
WHERE r.DateLogged >= '20150301'
AND r.DateLogged <= '20150817'
GROUP BY r.DateLogged;
注意,我已将您的日期格式更改为完全独立于文化的格式yyyyMMdd
,这是SQL Server中DATETIME
和SMALLDATETIME
的唯一独立格式,因此虽然略微不易清晰,它保证了正确的转换,对于某些区域设置,格式yyyy/MM/dd
将引发错误,或者更糟糕的是它将被转换为非预期的日期。
SET DATEFORMAT DMY;
SELECT CONVERT(DATETIME, '2015/08/17')
我还将您的BETWEEN
条款更改为>=
和<=
,不是因为它有任何不同,而是因为它更容易转换为开放日期范围,例如< / p>
WHERE r.DateLogged >= '20150301'
AND r.DateLogged < '20150818'
使用between '2015/03/01' and '2015/08/17'
,您可能会记录2015/08/17 10:00
的日期,但不会返回,并且通常不直观。如需更多阅读,请参阅What do BETWEEN and the devil have in common?。