代码之家  ›  专栏  ›  技术社区  ›  Mario

如何对每行的最小计算值求和?

  •  0
  • Mario  · 技术社区  · 7 年前

    SELECT 
        MONTHNAME(r.date_of_application) month_name,
        MONTH(r.date_of_application) month,
        SUM(CASE
            WHEN status = 'pending' THEN 1
            ELSE 0
        END) pending,
        SUM(CASE
            WHEN status = 'attended' THEN 1
            ELSE 0
        END) attended,
        SUM(CASE
            WHEN status = 'absent' THEN 1
            ELSE 0
        END) absent,
        SUM(CASE
            WHEN status = 'canceled' THEN 1
            ELSE 0
        END) canceled
    FROM
        request r
            INNER JOIN
        user u ON u.id = r.user_id
    GROUP BY month_name , month
    ORDER BY 2 DESC;
    

    我得到这个结果

    +------------+-------+---------+----------+--------+----------+
    | month_name | month | pending | attended | absent | canceled |
    +------------+-------+---------+----------+--------+----------+
    | October    |    10 |       4 |        1 |      0 |        1 |
    +------------+-------+---------+----------+--------+----------+
    

    现在我想对列的值求和 pending attended , absent canceled total .

    这是预期的结果。

    +------------+-------+---------+----------+--------+----------+-------+
    | month_name | month | pending | attended | absent | canceled | total |
    +------------+-------+---------+----------+--------+----------+-------+
    | October    |    10 |       4 |        1 |      0 |        1 |    6 |
    +------------+-------+---------+----------+--------+----------+-------+
    

    此查询可能有许多结果

    1 回复  |  直到 7 年前
        1
  •  1
  •   Tim Biegeleisen    7 年前

    只需添加一个 COUNT(*) 用于捕获所有状态的全部计数的聚合项:

    SELECT 
        MONTHNAME(r.date_of_application) month_name,
        MONTH(r.date_of_application) month,
        COUNT(CASE WHEN status = 'pending'  THEN 1 END) pending,
        COUNT(CASE WHEN status = 'attended' THEN 1 END) attended,
        COUNT(CASE WHEN status = 'absent'   THEN 1 END) absent,
        COUNT(CASE WHEN status = 'canceled' THEN 1 END) canceled,
        COUNT(*) total
    FROM request r
    INNER JOIN user u
        ON u.id = r.user_id
    GROUP BY
        month_name , month
    ORDER BY 2 DESC;
    

    注意:如果你想要 total 只包括四个 status 当前正在清点的值,然后使用条件聚合:

    COUNT(CASE WHEN status IN ('pending', 'attended', 'absent', 'cancelled')
               THEN 1 END) AS total