我希望为某些不同类型的作业获取某些表的聚合值。我可以将这3个查询合并到一个查询中吗?
SELECT
COUNT(*) AS totaljobs,
SUM(filesize) AS totalfilesize
FROM Job
SELECT
COUNT(*) AS assignedjobs,
SUM(filesize) AS assignedjobs
FROM Job
JOIN Assignment ON Assignment.job_id = Job.id
SELECT
COUNT(*) AS unassignedjobs,
SUM(filesize) AS unassignedjobs
FROM Job
LEFT JOIN Assignment ON Assignment.job_id = Job.id
WHERE Assignment.job_id IS NULL
查询的行为与您预期的一样,例如: totaljobs = assignedjobs + unassignedjobs
。我觉得有一种方法可以在一个查询中更有效地完成它,但我不知道如何。
答案 0 :(得分:0)
试试这个
SELECT
SUM(case when Assignment.job_id IS NOT NULL then 1 else 0 end) AS assignedjobs,
SUM(case when Assignment.job_id IS NULL then 1 else 0 end) AS unassignedjobs,
COUNT(*) as totaljobs
FROM Job
LEFT JOIN Assignment ON Assignment.job_id = Job.id