是否可以在SQL中有条件地返回字段?

时间:2017-04-12 12:36:08

标签: sql sql-server conditional

我想构建一个查询,如果任务非常晚/晚/接近按时/按时返回。

任务状态: 早2天

如果时间接近-1天

迟到1天

如果2天后会发生变化

我尝试了什么:

SELECT field_1, diff,
COUNT(CASE WHEN diff <= -2 THEN 1 END) onTime,
COUNT(CASE WHEN diff <= -1 THEN 1 END) nearOnTime,
Count(CASE WHEN diff >= 2 THEN 1 END) veryLate,
Count(CASE WHEN diff >= 0 THEN 1 END) Late
FROM(
     SELECT field_1, DATEDIFF(day,Max(predicted_date), realization_date) as diff
     FROM table
     Group by field_1, realization_date
     HAVING end_date is not null) as req1
GROUP BY field_1, diff) 

diff:谓词日期和实现日期之间的差异    =&GT;返回这两个日期之间的天数

它返回:

field_1  |  diff  |  onTime  |  nearOnTime  |  veryLate  |  Late
---------+--------+----------+--------------+------------+-------
 task1   |   -3   |     1    |      1       |     0      |   0
 task2   |    2   |     0    |      0       |     1      |   1

我认为我的方法很糟糕,那么返回任务状态的选择是什么?

1 个答案:

答案 0 :(得分:3)

也许是这些方面的东西..(小提琴会有所帮助 - 这还没有经过测试)

SELECT field_1, diff,
CASE WHEN diff <= -2 THEN 'On Time',
WHEN diff <= -1 THEN 'nearOnTime',
WHEN diff >= 2 THEN 'veryLate',
WHEN diff >= 0 THEN 'Late'
else 'OK'  END as status
FROM(
     SELECT field_1, DATEDIFF(day,Max(predicted_date), realization_date) as diff
     FROM table
     Group by field_1, realization_date
     HAVING end_date is not null) as req1
GROUP BY field_1, diff)