按小时从MYSQL数据库中对数据进行排序

时间:2013-09-13 17:40:35

标签: mysql

我有db中的用户,我希望按小时排序并显示当时注册的用户数。

select
  date_format(create_time, '%Y-%m-%d %h%p') as date,
  count(id) as 'Number of registrations'
from users
group by 1
order by 1 desc
;

以上代码可行;但是,我想要做的是显示0没有用户注册的小时数。例如,如果在下午5点没有注册,这将跳过下午5点的行,这是合乎逻辑的。有没有办法实现我的目标?

2 个答案:

答案 0 :(得分:1)

你可以使用这样的查询:

select
  date_format(t.d + INTERVAL t.h HOUR, '%Y-%m-%d %h%p') as date,
  count(id) as 'Number of registrations'
from (
  SELECT *
  FROM
    (SELECT DISTINCT DATE(create_time) d FROM users) dates,
    (SELECT 0 h UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
    UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7
    UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11
    UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15
    UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19
    UNION ALL SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23) hours
  ) t LEFT JOIN users
  ON DATE(users.create_time)=t.d AND HOUR(users.create_time)=t.h
group by t.d, t.h
order by t.d, t.h

请参阅小提琴here

答案 1 :(得分:1)

您需要生成所有可能的日期和小时组合。

假设您每天至少有一条记录,每小时至少有一条记录,您可以这样做:

select concat(d.theday, ' ', h.thehour) as date,
       count(id) as 'Number of registrations'
from (select distinct date_format(create_time, '%Y-%m-%d') as theday from users
     ) d cross join
     (select distinct date_format(create_time, '%h%p') as thehour from users
     ) h left outer join
     users u
     on date_format(u.create_time, '%Y-%m-%d %h%p) = concat(d.theday, ' ', h.thehour)
group by concat(d.theday, ' ', h.thehour)
order by 1 desc;