SQL:如何获取计数值的 sum() [重复]
Posted
技术标签:
【中文标题】SQL:如何获取计数值的 sum() [重复]【英文标题】:SQL: how to get sum() of counted values [duplicate] 【发布时间】:2013-09-23 10:43:28 【问题描述】:我使用以下语句读出用户注册
SELECT DAY(p.creationInstant) as day, MONTH(p.creationInstant) as month,
YEAR(p.creationInstant) as year, count(p.id) as users
FROM person p WHERE p.enrollmentStatus ="Enrolled"
GROUP BY year, month, day
ORDER BY year, month, day
这会给我以下输出:
day month year users
1 1 2013 3
2 1 2013 5
3 1 2013 7
...
现在我想有一个总结用户的第四列:
day month year users **totalUsers**
1 1 2013 3 3
2 1 2013 5 8
3 1 2013 7 15
...
但不知何故,我无法弄清楚如何使用 SQL (dbms: mysql) 来做到这一点。
【问题讨论】:
查看运行总计,例如***.com/questions/664700/… 也有用的阅读:***.com/questions/15101941/… “running totals”本来就是搜索词!天啊...有时我的母语是英语...谢谢@StuartLC 【参考方案1】:这就是我的陈述在提示“运行总计”问题后的处理方式,它就像一个魅力:
SET @runtot:=0;
SELECT q1.day, q1.month, q1.year, q1.users,
(@runtot := @runtot + q1.users) AS totalUsers
FROM (
SELECT DAY(p.creationInstant) as day, MONTH(p.creationInstant) as month,
YEAR(p.creationInstant) as year, count(p.id) as users
FROM PERSON p where p.enrollmentStatus ="Enrolled"
GROUP BY year, month, day
ORDER BY year, month, day) as q1
【讨论】:
【参考方案2】:select day,
month,
year,
(SELECT sum(a.id)
FROM person a
WHERE a.enrollmentStatus = "Enrolled"
and DAY(a.creationInstant) <= b.day)
from (SELECT DAY(p.creationInstant) as day,
MONTH(p.creationInstant) as month,
YEAR(p.creationInstant) as year,
count(p.id) as users
FROM person p
WHERE p.enrollmentStatus = "Enrolled"
GROUP BY year, month, day
ORDER BY year, month, day) b
【讨论】:
以上是关于SQL:如何获取计数值的 sum() [重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 SQL 获取 2 列之间日期差异的计数(值的分布)?