我有一张名为" AGGREGATEVALUE"在数据库模式" CLOUD"。我正在使用PostgreSQL:
CREATE TABLE CLOUD.AGGREGATEVALUE(
id SERIAL,
value CLOUD.FLOATVALUE NOT NULL,
idBoard VARCHAR(32),
idParameterRegolator VARCHAR(32),
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
FOREIGN KEY(idBoard) REFERENCES CLOUD.BOARD(id),
FOREIGN KEY(idParameterRegolator) REFERENCES CLOUD.PARAMETERREGOLATOR(id)
);
以下是此表格实例的示例(使用简单选择获取所有关于idboard='board1'
的内容)
id | value | idboard | idparameterregolator | timestamp
----+-------+---------+----------------------+----------------------------
1 | 1.00 | board1 | param1 | | 2014-08-24 10:29:33.677425
2 | 2.00 | board1 | param1 | | 2014-08-24 10:29:39.507868
3 | 4.00 | board1 | param1 | | 2014-08-24 10:29:46.286815
4 | 5.00 | board1 | param1 | | 2014-08-24 10:29:53.513363
5 | 1.00 | board1 | param2 | | 2014-08-24 10:29:58.252255
6 | 2.00 | board1 | param2 | | 2014-08-24 10:30:02.265151
7 | 3.00 | board1 | param2 | | 2014-08-24 10:30:05.480344
8 | 4.00 | board1 | param2 | | 2014-08-24 10:30:08.281917
9 | 5.00 | board1 | param2 | | 2014-08-24 10:30:10.845078
10 | 1.00 | board1 | param3 | | 2014-08-24 10:30:15.708794
11 | 2.00 | board1 | param3 | | 2014-08-24 10:30:18.82404
12 | 3.00 | board1 | param3 | | 2014-08-24 10:30:22.082542
13 | 4.00 | board1 | param3 | | 2014-08-24 10:30:24.662375
14 | 5.00 | board1 | param3 | | 2014-08-24 10:30:27.994689
假设从上表开始,我需要的是获得另一张表:
value | idparameterregolator | timestamp
----------------------------------------------------------
5.00 | param1 | 2014-08-24 10:29:53.513363
5.00 | param2 | 2014-08-24 10:30:10.845078
5.00 | param3 | 2014-08-24 10:30:27.994689
也就是说,我需要为每个参数获取具有最后一个时间戳值的相应值。
我尝试使用ORDER BY
子句但没有任何结果。
答案 0 :(得分:1)
distinct on
2值的 order by
可以解决问题。
SELECT distinct on(value) *
FROM CLOUD.AGGREGATEVALUE
ORDER BY value, TIMESTAMP DESC;
答案 1 :(得分:0)
标准方式,避免聚合:
SELECT * FROM AGGREGATEVALUE av
WHERE NOT EXISTS (
SELECT * FROM AGGREGATEVALUE nx
WHERE nx.idparameterregolator =av.idparameterregolator
AND nx.idboard = av.idboard
AND nx.ztimestamp > av.ztimestamp
);
注意:我将timestamp
替换为ztimestamp
,因为它是一个保留字。