2013-05-15 302 views
1

我對Postgres的4臺具有下列組織與where子句

reads: 
id -- primary key 
value -- integer 
read_datetime -- datetime 
patient_id -- integer 
reader_id -- integer 

readers: 
id -- primary key 

patient_readers: 
id -- primary key 
patient_id -- integer 
reader_id -- integer 
issuance_datetime -- datetime 
unassignment_datetime -- datetime 
issued_value -- integer 

patients: 
id -- integer 

我想創建一個查詢在那裏我可以得到一個特定的閱讀最新發布的信息Postgres的窗口功能。到目前爲止,我有以下查詢

SELECT 
value, 
read_datetime, 
issued_value, 
issuance_datetime, 
unassignment_datetime 
FROM "reads" 
INNER JOIN "readers" ON "readers"."id" = "reads"."reader_id" 
INNER JOIN "patient_readers" ON "patient_readers"."reader_id" = "readers"."id" AND patient_readers.patient_id = reads.patient_id 
INNER JOIN patientsON patients.id = reads.patient_id 
ORDER BY reads.patient_id , read_datetime, issuance_datetime 

這將產生輸出,其中一組行的是低於發行信息以外的所有信息相同(issuance_datetime,unassignment_datetime和issued_value),因爲我期望的那樣。我想聚集相對於發行信息readers.id和patients.id,然後我就只喜歡一組發佈的信息,其中

read_datetime > issuance_datetime AND (
    (unassignment_datetime IS NOT NULL AND read_datetime < unassignment_datetime) OR 
    (NEXT(issuance_datetime) IS NOT NULL AND read_datetime < NEXT(issuance_datetime) OR 
    (NEXT(issuance_datetime) IS NULL) 

在這裏,我做了功能NEXT()但基本上我想就窗口向前看一行。我也想在窗口中做一個WHERE子句(或者看起來像這樣)。我剛剛開始閱讀關於窗口函數的內容,所以很多這些對我來說都是新的(我並不確定窗口函數是我想要的),所以我希望這可以在Postgres中解決。

感謝

回答