gpt4 book ai didi

mysql - 每天计数(mysql)

转载 作者:行者123 更新时间:2023-11-30 21:41:47 25 4
gpt4 key购买 nike

I want get something like this

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 

关于如何为此创建查询的一些提示?

最佳答案

我建议在 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)

关于mysql - 每天计数(mysql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51219026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com