每天的计数(mysql)

ijxebb2r  于 2021-06-24  发布在  Mysql
关注(0)|答案(4)|浏览(254)

我想要这样的东西
mysql数据

(dat_reg)
1.1.2000 
1.1.2000 
1.1.2000
2.1.2000
2.1.2000
3.1.2000

我想得到:

(dat_reg)  (count)
    1.1.2000 -   3
    2.1.2000 -   5
    3.1.2000 -   6

我尝试的是:

SELECT COUNT( * ) as a , DATE_FORMAT( dat_reg, '%d.%m.%Y' ) AS dat 
FROM members 
WHERE (dat_reg > DATE_SUB(NOW() , INTERVAL 5 DAY)) 
GROUP BY DATE_FORMAT(dat_reg, '%d.%m.%Y') 
ORDER BY dat_reg

但我得到:

1.1.2000 - 3 | 2.1.2000 - 2 | 3.1.2000 - 1

如何为此创建查询的一些技巧?

2nbm6dog

2nbm6dog1#

我建议在mysql中使用变量:

SELECT d.*, (@sumc := @sumc + cnt) as running_cnt
FROM (SELECT DATE_FORMAT(dat_reg, '%d.%m.%Y') as dat, COUNT(*) as cnt
      FROM members 
      WHERE dat_reg > DATE_SUB(NOW() , INTERVAL 5 DAY) 
      GROUP BY dat
      ORDER BY dat_reg 
     ) d CROSS JOIN
     (SELECT @sumc := 0) params;

如果要从时间开始累计,则需要一个附加的子查询:

SELECT d.*
FROM (SELECT d.*, (@sumc := @sumc + cnt) as running_cnt
      FROM (SELECT DATE_FORMAT(dat_reg, '%d.%m.%Y') as dat, dat_reg, COUNT(*) as cnt
            FROM members 
            GROUP BY dat
            ORDER BY dat_reg 
           ) d CROSS JOIN
           (SELECT @sumc := 0) params
      ) d
WHERE dat_reg > DATE_SUB(NOW() , INTERVAL 5 DAY)
tcomlyy6

tcomlyy62#

我相信你可以使用窗口功能来完成这项工作:

mysql> SELECT employee, sale, date, SUM(sale) OVER (PARTITION by employee ORDER BY date) AS cum_sales FROM sales;
+----------+------+------------+-----------+
| employee | sale | date       | cum_sales |
+----------+------+------------+-----------+
| odin     |  200 | 2017-03-01 |       200 |
| odin     |  300 | 2017-04-01 |       500 |
| odin     |  400 | 2017-05-01 |       900 |
| thor     |  400 | 2017-03-01 |       400 |
| thor     |  300 | 2017-04-01 |       700 |
| thor     |  500 | 2017-05-01 |      1200 |
+----------+------+------------+-----------+

在您的情况下,您已经拥有了正确的组,只需指定数据聚合的顺序即可。
资料来源:https://mysqlserverteam.com/mysql-8-0-2-introducing-window-functions/
干杯

mv1qrgav

mv1qrgav3#

计算注册日期小于或等于当前注册日期的行的子查询可以帮助您解决此问题。

SELECT m2.dat_reg,
       (SELECT count(*)
               FROM members m3
               WHERE m3.dat_reg <= m2.dat_reg) count
       FROM (SELECT DISTINCT m1.dat_reg
                    FROM m1.members
                    WHERE m1.dat_reg > date_sub(now(), INTERVAL 5 DAY)) m2
       ORDER BY m2.dat_reg;

(如果有天没有人注册,并且不想在结果中出现空白,则需要替换别名的子查询 m2 对于表或子查询,其所有日期都在各自的范围内。)

7kqas0il

7kqas0il4#

以下是使用秩和连续计数变量的解决方案:

WITH ranked AS (
  SELECT m.* 
    ,ROW_NUMBER() OVER (PARTITION BY m.dat_reg ORDER BY m.id DESC) AS rn
  FROM (
    select id, dat_reg
    ,@cnt := @cnt + 1 AS ccount from members
    ,(SELECT @cnt := 0) var 
   WHERE (dat_reg > DATE_SUB(NOW(), INTERVAL 5 DAY))
  ) AS m
)
SELECT DATE_FORMAT(dat_reg, '%d.%m.%Y') as dat, ccount FROM ranked WHERE rn = 1;

小提琴

相关问题