0

我想为某些不同类型的工作获取表格的一些聚合值。我可以将这 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. 我觉得有办法在一个查询中更有效地做到这一点,但我不知道如何。

4

1 回答 1

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
于 2013-10-30T10:23:55.200 回答