我想根据表格中的条件订购Postgres查询
id sensor_id alarmTime clearedTime
415068 3734 2016-04-20 12:25:32 2016-04-27 21:05:44
415070 3734 2016-04-21 12:25:32 null
415071 3734 2016-03-22 12:25:32 2016-04-29 21:15:44
415072 3734 2016-04-23 12:25:32 null
415073 3734 2016-04-20 12:25:32 2016-04-22 22:05:45
415074 3734 2016-02-26 12:25:32 2016-04-27 23:15:24
从上面的表格中,我想首先按空值排序,然后按报警时间排序,其余行仅按清除时间排序。得到这样的东西
id sensor_id alarmTime clearedTime
415070 3734 2016-04-21 12:25:32 null
415072 3734 2016-04-23 12:25:32 null
415068 3734 2016-04-20 12:25:32 2016-04-27 21:05:44
415073 3734 2016-04-20 12:25:32 2016-04-22 22:05:45
415071 3734 2016-03-22 12:25:32 2016-04-29 21:15:44
415074 3734 2016-02-26 12:25:32 2016-04-27 23:15:24
我尝试过这样的事情
select * from table
ORDER BY
case alarm.clearedTime is NOT NULL
when TRUE THEN alarmTime
else clearedTime
end DESC NULLS FIRST;
答案 0 :(得分:1)
尝试
ORDER BY COALESCE(clearedTime, alarmTime)
或类似的东西。
ORDER BY CASE
WHEN clearedTime IS NULL THEN NULL
ELSE 1
END NULLS FIRST,
alarm.alarmTime DESC,
alarm.clearedTime DESC -- optional to solve tie between 415068 and 415073
答案 1 :(得分:0)
这个怎么样?
order by alarm.clearedTime nulls first, alarm.alarmTime