gpt4 book ai didi

sql - PostgreSQL聚合函数选择2个对应字段

转载 作者:行者123 更新时间:2023-11-29 13:51:24 25 4
gpt4 key购买 nike

我有以下子查询:

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

这给了我正确的测试日期。但是,我还需要与日期对应的 testschedule."testresult_id"。有没有办法从上面的查询中选择这个?

最佳答案

您可以摆弄窗口函数,或者在最新版本中,进行左侧连接:

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 子句中。

关于sql - PostgreSQL聚合函数选择2个对应字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com