2017-08-03 54 views
0

我有一个表,如下所示:Postgres的时期查询

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

请加预期的结果为上述数据集。 –

+0

为perid'timestamp> ='2014-07-11''选择所有类型,我想要除了4之外的所有行(因为2014-07-11之前类型B的最后一个值在第2行) – Miro

回答

0

您可以使用窗口函数特别是排名():

https://www.postgresql.org/docs/current/static/tutorial-window.html

,你将有somethink这样的:

select * from (
    select ...., rank() over (partition by type order by timestamp desc) as rk 
    where ... 
) where rk=1; 

我不记得,如果你可以将'rk'放入内部查询的'having'子句中,但我确信我已经尝试过一次了,而且postgres的确做到了不接受

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