gpt4 book ai didi

sql - 在 Postgresql 中删除子查询

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

WITH Dept(DName) AS (
VALUES ('D1'), ('D2'), ('D3')
) ,
Emp(DName, EName, Age, Loc) AS (
VALUES ('D1','E11',20,'L1'), ('D1','E12',25,'L2'),('D2','E21',28,'L1')
)
SELECT DName,

(SELECT avg(Age)
FROM Emp
WHERE Loc = 'L1'
AND DName = d.DName) AS "L1 Avg",

(SELECT avg(Age)
FROM Emp
WHERE Loc = 'L2'
AND DName = d.DName) AS "L2 Avg"
FROM Dept d
LEFT JOIN Emp USING (DName)
GROUP BY DName

这个查询的输出是:

"D1";20.0000000000000000;25.0000000000000000
"D2";28.0000000000000000;
"D3";;

有没有办法通过删除子查询并用 Postgresql 中更好的结构替换它来重构查询?

最佳答案

SELECT DName,
avg(case when loc = 'L1' then age else null end) as "L1 Avg",
avg(case when loc = 'L2' then age else null end) as "L2 Avg"
FROM Dept d
LEFT JOIN Emp USING (DName)
GROUP BY DName

关于sql - 在 Postgresql 中删除子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14827567/

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