【问题标题】:If tag from subtask empty, inherit tag from parent task如果子任务的标签为空,则继承父任务的标签
【发布时间】:2016-08-01 19:21:55
【问题描述】:

我有两个表,我想获取按标签分组的任务的记录分钟总和,大多数情况下子任务与父任务具有相同的标签,但在某些情况下,它们没有。

我怎样才能得到按标签分组的记录分钟总和,包括子任务,所以如果他们没有标签,他们会从他们的父母那里继承标签。

任务

+-----+-----------+------+-------+------------+
| id  | parent-id | name |  tag  | is-subtask |
+-----+-----------+------+-------+------------+
| 001 |           | a    | sales |          0 |
| 002 |       001 | b    | sales |          1 |
| 003 |       001 | c    |       |          1 |
| 004 |           | d    | store |          0 |
+-----+-----------+------+-------+------------+

+-----+---------+-------------+----------------+
| id  | task-id | description | logged-minutes |
+-----+---------+-------------+----------------+
| 991 |     001 | Time for a  |             15 |
| 992 |     002 | Time for ab |             60 |
| 993 |     002 | Time for ab |             75 |
| 994 |     003 | Time for ac |             35 |
| 995 |     004 | Time for d  |             20 |
+-----+---------+-------------+----------------+

【问题讨论】:

    标签: mysql sql group-by coalesce


    【解决方案1】:

    基本上你需要使用COALESCE() 函数,它返回列表中找到的第一个非空值(如果只有空值,则计算结果为空)。

    在您从派生表(查询的内部部分)获得有关标签的信息后,您可以将该信息连接到times 表以计算每个标签的总和。

    我没有测试过代码,但我相信它应该可以工作 - 这假设你的关系只有 1 级深。如果您有更深的层次结构,请查看 How to create a MySQL hierarchical recursive query 以了解对此代码的一些调整。

    SELECT
        alltasks.tag
      , SUM( times.logged-minutes ) AS logged-minutes
    FROM (
        -- take parent tasks
        SELECT
            tparent.id
          , tparent.tag
        FROM task tparent
        UNION
        -- take child tasks
        SELECT
            tchild.id
          , COALESCE( tchild.tag, tparent.tag ) -- if no child tag, use parent tag
        FROM task tparent
        INNER JOIN task tchild ON 
          tparent.id = tchild.parent-id
          AND tchild.is-subtask = 1 -- may not be necessary unless you have different relationships
        ) alltasks
    LEFT JOIN times ON 
      alltasks.id = times.task-id
    GROUP BY alltasks.tag
    

    【讨论】:

      猜你喜欢
      • 2020-10-15
      • 2017-12-23
      • 1970-01-01
      • 2012-10-25
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 2011-09-22
      相关资源
      最近更新 更多