3
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 でより適切な構造に置き換える方法はありますか?

4

1 に答える 1

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
于 2013-02-12T08:15:26.937 に答える