gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:01:49 25 4
gpt4 key购买 nike

我正在尝试重置每种 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com