删除Postgresql中的子查询

时间:2013-02-12 07:31:28

标签: sql postgresql join subquery

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中更好的构造?

1 个答案:

答案 0 :(得分:2)

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