我正在尝试重置每种insurance_status的累积计数。现在,我的代码恢复了累计计数,但是当insurance_status更改时并没有重新开始。 如何设置查询的分组依据或重置变量以获取所需的查询。
我试图在代码中最后一个命令之前添加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;
答案 0 :(得分:0)
您需要另一个变量来记住保险状态:
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
中表达式的计算顺序,因此您不能在一个表达式中分配变量,而在另一个表达式中使用它们。