子查询没有输出正确的结果?

时间:2016-01-08 21:54:25

标签: mysql sql select

我希望有人可以帮我解决这个问题,我一直尝试不同的组合,但似乎无法得到正确的结果。

首先,我有3个表,类别,部门和主人,主人有FK。我希望获得每个部门的总时间和按部门分类的总时间总和,以便我可以看到哪个部门有多少时间用于该类别,所有部门应按部门分组并按正确的顺序排列?

我可以得到结果但是没有出来,这是我的代码......

SELECT a.department, time_spent , COUNT(DISTINCT (a.department)), sum_quarantine FROM 

    (SELECT d.department, SUM(time_spent) as time_spent
    FROM master as m 
    INNER JOIN department as d ON d.dept_id = m.dept_id GROUP BY d.department) AS a,

    (SELECT d.department, c.category, SUM(time_spent) as sum_quarantine
    FROM master as m
    INNER JOIN category as c ON c.cat_id = m.cat_id
    INNER JOIN department as d ON d.dept_id = m.dept_id
    WHERE category = 'Quarantine' GROUP BY d.department) as b

    GROUP BY b.department

1 个答案:

答案 0 :(得分:0)

您可以在没有子查询的情况下完成所需的工作,在CASE WHEN中使用SUM,以便它只对您感兴趣的内容进行求和('隔离'):

SELECT     d.department, 
           SUM(CASE c.category
                 WHEN 'Quarantine' THEN time_spent
               END) as sum_quarantine,
           SUM(time_spent) time_spent,
           COUNT(DISTINCT (c.category)) category_count
FROM       master as m
INNER JOIN category as c ON c.cat_id = m.cat_id
INNER JOIN department as d ON d.dept_id = m.dept_id
GROUP BY   d.department
ORDER BY   1

这是fiddle

请注意,我也添加了一个计数,因为您尝试了一个计数。但是你的总是会返回1,所以我不确定你在寻找什么。我添加了与该部门相关联的类别数量。

此外,您没有指定所需的顺序,但很容易调整ORDER BY子句。上面的查询按部门排序结果,但是如果您想按第二列按降序排序,则执行:

...
ORDER BY 2 DESC

如果您的结果包含 NULL 值,并且您希望改为使用零,那么请使用COALESCE函数。例如:

COALESCE(SUM(time_spent), 0) time_spent,