MySQL按日期分组查询截至到当天的注册用户总数
迷茫
迷茫 2017-04-17 13:34:58
[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

注:

  • 从2015-12-02开始分组;

  • 但count结果中包含在此之前的数据;

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

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

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

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

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(2)
黄舟

这是个什么需求。写出来了,不知道符合你的需求不?
在线调试地址: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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号