按日期和较旧分组的行数

时间:2017-04-29 14:38:13

标签: mysql

我有一张表,其中包含一个事件注册记录。

table data

我可以按日期分组注册 -

SELECT DATE(`date_registered`) as `date`, COUNT(*) as `total`  
FROM `registration`
GROUP BY DATE(`date_registered`)

count by date

但我希望根据日期得到运行计数 -
count by date all

所以我正在做类似的事情 -

SELECT DATE(`date_registered`) as `date`, COUNT(*) as `total`  
FROM `registration`
GROUP BY DATE(`date_registered`) <= DATE(`date_registered`)

我尝试使用前面所有日期的计数LEFT JOIN,但这不起作用 -

SELECT DATE(r1.`date_registered`) as `date`, COUNT(*)+r3.preTotal as `total`
FROM `registration` r1
LEFT JOIN (
  SELECT COUNT(*) as preTotal
  FROM `registration` r2
  WHERE DATE(r2.`date_registered`) < DATE(r1.`date_registered`)
  ) r3
GROUP BY DATE(r1.`date_registered`)

我创建了一个SQLFiddle
基本计数 - http://sqlfiddle.com/#!9/420d1d/5
我失败的尝试 - http://sqlfiddle.com/#!9/420d1d/6

我认为我错过了一种简单的方式。

修改 在rextester.com上也是如此 基本计数 - http://rextester.com/GISU91151
尝试失败 - http://rextester.com/RDTFK34261

2 个答案:

答案 0 :(得分:2)

实现这项工作的一种方法是创建一个核心子查询。

<强>查询

SELECT
     registration_counted.date
  , (registration_counted.total + registration_counted.preCount) AS total  
FROM ( 

  SELECT
     DATE(date_registered) AS DATE 
   , COUNT(*) AS total
   , ( 
     SELECT 
       COUNT(*) 
     FROM 
       registration AS registration2
     WHERE
       DATE(registration2.date_registered) < DATE(registration1.date_registered) 
     )
    AS
      preCount
   FROM 
      registration AS registration1
   GROUP BY 
     DATE(date_registered)

  ORDER BY 
    DATE(date_registered) ASC

)
  AS 
    registration_counted

<强>结果

date         total  
----------  --------
2014-01-16         1
2014-01-20         2
2014-01-22         3
2014-01-31        18
2014-02-01        19
2014-02-04        22
2014-02-12        23
2014-02-19        24
2014-02-20        28
2014-02-26        30
2014-02-27        34
2014-02-28        37

答案 1 :(得分:2)

这个怎么样:

SELECT
  DATE(`date_registered`) AS date,
  (
    SELECT COUNT(*)
    FROM  `registration` t2
    WHERE DATE(t2.`date_registered`) <= DATE(t1.`date_registered`)
  ) AS total
FROM  `registration` t1
GROUP BY DATE(`date_registered`);