Gopal
Gopal

Reputation: 1452

Remove a Subquery in Postgresql

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

The output of this query is:

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

Is there a way to refactor the query by removing the subquery and replace it with a better construct in Postgresql?

Upvotes: 3

Views: 366

Answers (1)

user330315
user330315

Reputation:

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

Upvotes: 2

Related Questions