立即免责声明:我已经有几年没认真做 SQL 了,最近又回来了。
给定一个表:
logical_id, instance_id, node_id, state, time_stamp
1, 1, a, starting, 1300003234
2, 1, a, up, 1300003235
**3, 1, b, starting, 1300003237**
4, 1, a, completed, 1300003239
5, 1, a, shutdown, 1300003240
给定一个特定的instance_id(例如1)我想得到权威节点的最后一个状态记录(单行-粗体突出显示),权威节点是最近进入'starting'的节点,在没有任何节点进入起始阶段,它只是要记录的最新节点。
我想我按 node_id 和 order by(而不是 filter)boolean(state = 'starting), time_stamp desc 做一些表格分组,但我似乎做不对,此外我认为分组必须在订购后进行。
我使用的是 postgres 9.x
最佳答案
这将检索最近的状态节点,如果它存在,否则它只会返回最近的非起始节点。
SELECT U.logical_id, U.instance_id, U.node_id, U.state, U.time_stamp
FROM
(
SELECT M1.logical_id, M1.instance_id, M1.node_id, M1.state, M1.time_stamp, 1 AS node_type
FROM MyTable M1
WHERE M1.instance_id=1 AND M1.state='starting'
ORDER BY M1.time_stamp DESC LIMIT 1
UNION
SELECT M2.logical_id, M2.instance_id, M2.node_id, M2.state, M2.time_stamp, 0 AS node_type
FROM MyTable M2
WHERE M2.instance_id=1
ORDER BY M2.time_stamp DESC LIMIT 1
) AS U
ORDER BY U.node_type DESC LIMIT 1
关于sql - Groupby排序和单行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11579709/