选择天

时间:2016-10-24 16:45:41

标签: mysql

我正在尝试根据这样的用户表制作报告

CREATE TABLE `user` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,  
 `password` varchar(255) DEFAULT NULL,
 `register_date` datetime DEFAULT NULL,
 `username` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

我需要显示在一段时间内注册了多少用户。我试试这个

SELECT COUNT(u.id) as "user_count" FROM user u WHERE u.register_date > '2016-01-01' AND u.register_date < '2016-10-24';

有一种方法可以白天制作吗?即我有initDate和endDate,我得到了今天之间每天注册的用户数量。例如

day = 2016-10-23

user_count = 2

day = 2016-10-24

user_count = 5

day = 2016-10-25

user_count = 0

3 个答案:

答案 0 :(得分:2)

您可以使用DATE()功能从日期时间列中提取DATE,然后GROUP BY这些日期:

SELECT DATE(u.register_date),COUNT(u.id) as "user_count" 
FROM user u
WHERE u.register_date > '2016-01-01' 
AND u.register_date < '2016-10-24'
GROUP BY DATE(u.register_date)
ORDER BY DATE(u.register_date);

答案 1 :(得分:0)

您可以使用DATE()功能获取register_date列中的日期,然后按其分组:

SELECT DATE(register_date) as registeringDay ,COUNT(u.id) as "user_count" FROM
    user WHERE u.register_date > '2016-01-01' AND u.register_date < '2016-10-24' 
    GROUP BY registringDay;

答案 2 :(得分:0)

只需按日期

将日期添加到查询和GROUP
SELECT COUNT(`id`) as `count`, `register_date`
FROM `user`
WHERE `register_date` BETWEEN '2016-01-01' AND '2016-10-24'
GROUP BY `register_date`;

如果register_date是DATETIME列

SELECT COUNT(`id`) as `count`, DATE(`register_date`) as `day`
FROM `user`
WHERE `register_date` BETWEEN '2016-01-01' AND '2016-10-24'
GROUP BY DATE(`register_date`);