2017-08-03 53 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