组合不同长度的SQL查询

时间:2017-04-28 05:32:53

标签: sql

我想知道如何将这两个查询结合起来。

-- gets average sick leave for females for each job
SELECT AVG(SickLeaveHours) AS FSickLeave
FROM Employees
WHERE Gender = 'female'
GROUP BY Job
ORDER BY FSickLeave DESC;

-- gets average sick leave for males for each job
SELECT AVG(SickLeaveHours) AS MSickLeave
FROM Employees
WHERE Gender = 'male'
GROUP BY Job
ORDER BY MSickLeave DESC;

我已经尝试过使用子查询和联合,但由于列长度不同而遇到了麻烦。

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

关键是将条件放在CASE表达式中,并且条件不匹配的位置将值设置为NULL以防止它成为{{1}的集合的一部分1}}' d:

AVG

答案 1 :(得分:0)

用户外部申请......

SELECT AVG(SickLeaveHours) AS FSickLeave,MSickLeave
FROM Employees
OUTER APPLY(
SELECT AVG(SickLeaveHours) AS MSickLeave
FROM Employees
WHERE Gender = 'male'
GROUP BY Job
ORDER BY MSickLeave DESC
) M1
WHERE Gender = 'female'
GROUP BY Job
ORDER BY FSickLeave DESC;