我有一个名为JOBS的数据库表,其中包含ID,STATUS和COMPLETION_TIME作为列。 STATUS 0,1成功,STATUS 2,3失败,STATUS 4,5被杀死。它只能有一个状态。我想找到在过去10小时内成功,失败和被杀的工作数量。我必须只使用SELECT作为查询,并且不能为查询提供任何变量。我使用以下查询进行操作。
SELECT
(SELECT COUNT(*)
WHERE STATUS IN (0,1))AS SuccessCount,
(SELECT COUNT(*)
WHERE STATUS IN (2,3))AS FailedCount ,
(SELECT COUNT(*)
WHERE STATUS IN (4,5))AS KilledCount,
FROM JOBS
WHERE COMPLETION_TIME >= (SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE()) - (10 * 60 * 60))
AND COMPLETION_TIME <= (SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE()));
但是这个查询不起作用。它给了我成功,失败或被杀的工作,而不是他们的工作。
答案 0 :(得分:0)
试试这个:
select sum(case when status in (0, 1) then 1 else 0 end) as succeeded,
sum(case when status in (2, 3) then 1 else 0 end) as failed,
sum(case when status in (4, 5) then 1 else 0 end) as killed
from jobs
WHERE COMPLETION_TIME >= (SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE()) - (10 * 60 * 60)) and
COMPLETION_TIME <= (SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE()));
您的原始查询在语法上不正确。我不知道它是如何返回任何数据的,因为子查询:
(SELECT COUNT(*) WHERE STATUS IN (0,1))
没有“FROM”子句来定义变量状态。