如何对每行中的迪南米计算值求和?

时间:2018-10-07 03:03:32

标签: mysql

在这种情况下,我需要您的建议。

具有以下SQL查询

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 |
+------------+-------+---------+----------+--------+----------+

现在,我想对列pendingattendedabsentcanceled的值求和,并将结果添加到新列total中。

这是预期的结果。

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

此查询可能有很多结果

预先感谢

1 个答案:

答案 0 :(得分:1)

只需添加一个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