mysql - 查询中的累积函数不会分组

标签 mysql sql mysql-workbench

我正在尝试重置每种 Insurance_status 的累积计数。现在我的代码返回了累积计数,但当 Insurance_status 更改时不会重新开始。 如何将查询设置为分组依据或重置变量以获得我想要的查询。

我尝试在代码中的最后一个 order by 之前添加 group by,但没有成功。

SELECT t.insurance_status, t.day, t.vendor_count,
       @running_total:=@running_total + t.vendor_count AS cumulative_sum
FROM (SELECT insurance_status,
             DATE_FORMAT(date, '%Y %m') as day,
             count(insurance_status) as vendor_count
      FROM vendor_report_jll
      WHERE project_id in (100, 92, 45, 91, 86, 87, 88, 40, 101, 90, 98)
      GROUP BY insurance_status,day
     ) t JOIN
     (SELECT @running_total := 0) AS t2
ORDER BY  t.insurance_status;

enter image description here

最佳答案

您需要另一个变量来记住保险状态:

SELECT t.insurance_status, t.day, t.vendor_count,
       (@sum := if(@is = t.insurance_status, @sum + t.vendor_count,
                   if(@is := t.insurance_status, t.vendor_count, t.vendor_count
                     )
                  )
       ) AS cumulative_sum
FROM (SELECT insurance_status,
             DATE_FORMAT(date, '%Y %m') as day,
             count(insurance_status) as vendor_count
      FROM vendor_report_jll
      WHERE project_id in (100, 92, 45, 91, 86, 87, 88, 40, 101, 90, 98)
      GROUP BY insurance_status, day
      ORDER BY insurance_status, day  -- just being explicit
     ) t CROSS JOIN
     (SELECT @sum := 0, @is := -1) params;

您需要在一条语句中完成所有分配。这是由于 MySQL 的规则所致 - 它不保证 SELECT 中表达式求值的顺序,因此您不能在一个表达式中分配变量并在另一个表达式中使用它们。

关于mysql - 查询中的累积函数不会分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56129002/

相关文章:

Mysql SELECT 查询名称忽略第一个单词,如果它是 "the", "a", "an"等

PHP识别计算机

php - 上传 .txt 文件并将内容插入数据库

c# - 存储 ASP.NET 4.5 MVC 用户数据的最佳方式

sql - 在 SQL 中使用两个表进行透视和逆透视(将值转置为列标题)

MYSQL Workbench 导出将无法在 mysql (Ubuntu) 中正确获取源代码

sql - 我应该执行什么 SQL 查询才能获得预期的结果集?

sql - 在bigquery中显示上个月的数据

MySQL 查询需要更多时间来获取数据 [MySQL]

mysql 工作台不显示列 - libglib2.0 问题