mysql - 如何对每行中的dinamilcy计算值求和?

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

现在我想将待处理已参加缺席已取消列的值相加,然后添加结果显示在新列total中。

这是预期的结果。

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

此查询可能有多个结果

提前致谢

最佳答案

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

关于mysql - 如何对每行中的dinamilcy计算值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52685103/

相关文章:

mysql 没有充分利用我的 cpu 和 ram?

ruby-on-rails - rails - 将复杂的可见性设置应用于思维狮身人面像结果

mysql - 为每行选择 x 天的 AVG

php - 错误 : undefined index?

MySQL 外键约束失败

android - 从数据库中获取空字符串时如何修复它?

php - SQL PHP : How to select some column from sql database and display it in PHP/HTML generated table in descending order where condition is. ..

PHP 表单 - 检查 mysql 是否已包含电子邮件数据

php - 如何在 yii 中设置命令超时?

php - 如何将 laravel 5.3 项目放在共享主机上