Groupby订购和单行选择

时间:2012-07-20 12:47:57

标签: sql postgresql

立即免责声明:自从我认真做了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)我想得到授权节点的最后一个状态记录(单行 - 以粗体突出显示),授权节点是最近进入'起始'的节点,在没有任何节点进入起始阶段,它只是要记录的最新节点。

我想我通过node_id 顺序做一些表格组(而不是过滤)boolean(state ='starting),time_stamp desc,但我似乎无法做到这一点,另外我认为小组必须在订购之后来。

我正在使用postgres 9.x

3 个答案:

答案 0 :(得分:1)

没关系,一旦不需要groupby,而不是ORDER BY(state ='starting')desc,time_stamp desc LIMIT 1似乎只为单个记录做了最后我选择了回答这个问题在霍尔格的集合中最好的

答案 1 :(得分:1)

这将检索最新的说明节点(如果存在),否则它将只返回最近的非起始节点。

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

答案 2 :(得分:0)

从表中选择*,其中instance_id = 1,time_stamp = max(time_stamp)和state ='starting';

你试过这条路吗?到达它的根时,时间戳或间隔很长。这可能会有所帮助,因为使用日期是某人永远不应该记住的事情之一

http://www.postgresql.org/docs/8.2/static/functions-datetime.html