SQL:如何获取计数值的sum()

时间:2013-09-23 10:43:29

标签: mysql sql

我正在使用以下语句来读出用户注册

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
...  

现在我想要一个总结用户的第4列:

day month year users **totalUsers**
  1     1 2013     3          3
  2     1 2013     5          8
  3     1 2013     7         15
...  

但不知怎的,我无法弄清楚如何用SQL(dbms:mySQL)来做到这一点。

2 个答案:

答案 0 :(得分:0)

这就是我的陈述如何看待“运行总计”问题的提示,它就像一个魅力:

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

答案 1 :(得分:0)

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