3

我在 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 点的行,这是合乎逻辑的。有没有办法实现我正在尝试的东西?

4

2 回答 2

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;
于 2013-09-13T18:07:38.250 回答
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

在此处查看小提琴。

于 2013-09-13T17:57:39.373 回答