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/

10-11 04:59