2016-11-18 85 views
1

我有以下子查詢:PostgreSQL的聚合函數選擇2個對應的字段

LEFT OUTER JOIN 
(
    SELECT 
     MAX(testresult."testdate") AS beforeresult, 
     testschedule."test_id", 
     testschedule."asset_id", 
     testschedule."testdate" AS testdate, 
     testschedule."testresult_id" as scheduleresult_id           
    FROM 
     "public"."testresult" testresult 
     INNER JOIN "public"."testschedule" testschedule 
      ON testschedule."asset_id" = testresult."asset_id" 
      AND testschedule."test_id" = testresult."test_id" 
    WHERE 
     "testresult"."client_id" = 25368272 
     AND testresult."testdate" < testschedule."mintolerancedate" 
     AND testschedule."testdate" > '2016-10-01' 
     AND testschedule."testdate" < '2016-10-20' 
    GROUP BY 
     testschedule."asset_id", 
     testschedule."test_id", 
     testschedule."testdate", 
     testschedule."testresult_id" 
    ORDER BY MAX(testresult."testdate") 
) lasttr 
    ON "testschedule"."asset_id" = lasttr."asset_id" 
    AND "testschedule"."test_id" = lasttr."test_id" 
    AND testschedule."testdate" = lasttr.testdate 

這給了我正確的testdate。但是,我還需要與日期對應的testchedule。「testresult_id」。有沒有辦法從上面的查詢中選擇這個?

在此先感謝

回答

0

您可以用窗口的功能,或在最近的版本不甘示弱,做了左側加入:

LEFT JOIN LATERAL 
(SELECT ts."test_id", ts."asset_id", ts."testdate" AS testdate, ts."testresult_id" as scheduleresult_id, 
     tr.* 
FROM "public"."testresult" tr INNER JOIN 
     "public"."testschedule" ts 
     ON ts."asset_id" = tr."asset_id" and ts."test_id" = tr."test_id" 
WHERE tr."client_id" = 25368272 AND 
     tr."testdate" < ts."mintolerancedate" AND 
     ts."testdate" > '2016-10-01' and ts."testdate" < '2016-10-20' AND 
     "testschedule"."asset_id" = ts."asset_id" AND 
     "testschedule"."test_id" = ts."test_id" 
ORDER BY tr."testdate" DESC 
FETCH FIRST 1 ROW ONLY 
) lasttr 

橫向聯接是像FROM子句中的相關子查詢。您可以根據需要返回任意數量的列。沒有ON子句,因爲連接條件位於子查詢的WHERE子句中。

+0

感謝您的快速響應,但我仍然沒有收到testschedule。「testresult_id」字段。基本上它需要以某種方式加入到testdate的MAX聚合函數中,但我似乎無法做到這一點 - 我的猜測是我忽略了一些簡單的東西。 – user3075171

+0

您不需要再次加入。側向連接應該做你想要的。 –

+0

所以我在每行之前加上「and」:「testschedule」。「」asset_id「= ts。」asset_id「 」testschedule「。」test_id「= ts。」test_id「然後當我運行這個時,當添加group by子句時,我得到「輸入結束時的語法錯誤」。如果我添加「ON」子句,那麼它會運行,但不會給出每個組的結果。 – user3075171