计算MySQL中的运行总计

编程入门 行业动态 更新时间:2024-10-26 22:22:43
本文介绍了计算MySQL中的运行总计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这个MySQL查询:

I have this MySQL query:

SELECT DAYOFYEAR(`date`) AS d, COUNT(*) FROM `orders` WHERE `hasPaid` > 0 GROUP BY d ORDER BY d

哪个返回如下内容:

d | COUNT(*) | 20 | 5 | 21 | 7 | 22 | 12 | 23 | 4 |

我真正想要的是末尾的另一列以显示运行总计:

What I'd really like is another column on the end to show the running total:

d | COUNT(*) | ??? | 20 | 5 | 5 | 21 | 7 | 12 | 22 | 12 | 24 | 23 | 4 | 28 |

这可能吗?

推荐答案

也许为您提供了一个更简单的解决方案,并且避免了数据库必须执行大量查询.这样只会执行一个查询,然后只需一次就可以对结果进行一些数学运算.

Perhaps a simpler solution for you and prevents the database having to do a ton of queries. This executes just one query then does a little math on the results in a single pass.

SET @runtot:=0; SELECT q1.d, q1.c, (@runtot := @runtot + q1.c) AS rt FROM (SELECT DAYOFYEAR(`date`) AS d, COUNT(*) AS c FROM `orders` WHERE `hasPaid` > 0 GROUP BY d ORDER BY d) AS q1

这将为您提供一个附加的RT(运行总计)列.不要错过顶部的SET语句来首先初始化运行的total变量,否则您将只获得一列NULL值.

This will give you an additional RT (running total) column. Don't miss the SET statement at the top to initialize the running total variable first or you will just get a column of NULL values.

更多推荐

计算MySQL中的运行总计

本文发布于:2023-10-30 22:21:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544173.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!