我有一张如下表所示的表格:
index | timestamp | type | value
------- | ----------------- | ---- | -----
1 | 2014-07-10 10:00 | A | 56
2 | 2014-07-10 11:04 | B | 69
3 | 2014-07-10 11:06 | C | 68
4 | 2014-07-10 10:03 | B | 60
5 | 2014-07-11 10:03 | B | 18
6 | 2014-07-11 11:03 | C | 48
我愿意为某些“类型”选择一段价值观。
问题是我还需要结果在所选时段开始之前包含每种类型的最后一个值。
是否可以通过单个查询(或列出有限数量的查询)来实现?
由于 梅尔
答案 0 :(得分:1)
最终我找到了自己的答案
SELECT timestamp, type, value
FROM table
where timestamp >= '2014-07-11'
UNION ALL
SELECT distinct on (type) timestamp, type, value
FROM table
where timestamp < '2014-07-11'
ORDER BY type, timestamp desc
答案 1 :(得分:0)
您可以使用窗口功能,尤其是rank():
https://www.postgresql.org/docs/current/static/tutorial-window.html
你会有一些想法:
select * from (
select ...., rank() over (partition by type order by timestamp desc) as rk
where ...
) where rk=1;
我不记得你是否可以将'rk'放在内部查询的'having'子句中,但我很确定我已经尝试了一次,并且postgres不接受