首页 > MySQL按日期分组查询截至到当天的注册用户总数

MySQL按日期分组查询截至到当天的注册用户总数

use_id reg_time
1      2015-12-01 08:08:08
2      2015-12-02 09:09:09
3      2015-12-02 13:08:08
4      2015-12-03 15:08:05
5      2015-12-03 17:08:08
6      2015-12-03 05:08:09

要得到:

reg_time   count
2015-12-02 3
2015-12-03 6

注:

我目前想到的方法是分2次查询:

  1. 首先统计出2015-12-02之前的count;

  2. 从2015-12-02开始分组查询每天的count;

  3. 在PHP中把 第1个步骤 和 当天之前的第2个步骤 中的count相加,再把结果各加入每个分组;

请问有没有方法一次查询出我要的结果?


这是个什么需求。写出来了,不知道符合你的需求不?
在线调试地址:SQL在线调试
截图:

SELECT reg_time, 
       total1, 
       @total := @total + total1 AS Counter 
FROM (select date(reg_time) as reg_time,count(user_id) as total1,(select count(*) from test) as sum from test group by date(reg_time)) as temp, (SELECT @total := 0) AS T1 
ORDER BY reg_time;

数据表结构:

/*
Navicat MySQL Data Transfer

Source Server         : local
Source Server Version : 50540
Source Host           : localhost:3306
Source Database       : test

Target Server Type    : MYSQL
Target Server Version : 50540
File Encoding         : 65001

Date: 2015-12-16 11:37:54
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `test`
-- ----------------------------
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `reg_time` datetime NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of test
-- ----------------------------
INSERT INTO `test` VALUES ('1', '2015-12-01 08:08:08');
INSERT INTO `test` VALUES ('2', '2015-12-02 09:09:09');
INSERT INTO `test` VALUES ('3', '2015-12-02 13:08:08');
INSERT INTO `test` VALUES ('4', '2015-12-03 15:08:05');
INSERT INTO `test` VALUES ('5', '2015-12-03 17:08:08');
INSERT INTO `test` VALUES ('6', '2015-12-16 21:00:00');
INSERT INTO `test` VALUES ('7', '2015-12-03 05:08:09');

select reg_time count(use_id) as count from (select use_id,date(reg_time) as reg_time  from reg) as tmp
【热门文章】
【热门文章】