这是一个包含用户、购物车
和时间
的表格。
一个用户
可以拥有多个购物车
。所有匿名用户
都有userId = 1000
;任何已识别用户的 ID 均不同于 1000
。
所有 cartId
都是唯一的。
+------------+-------------+----------------------+
| userId | cartId | time |
+------------+-------------+----------------------+
| 7650 | 231 | 2014-08-27 13:41:02 |
+------------+-------------+----------------------+
| 7632 | 221 | 2014-08-27 13:42:02 |
+------------+-------------+----------------------+
| 7650 | 289 | 2014-08-27 14:13:02 |
+------------+-------------+----------------------+
| 1000 | 321 | 2014-08-27 14:41:02 |
+------------+-------------+----------------------+
| 7650 | 500 | 2014-08-27 17:41:02 |
我有兴趣按一天中的某个小时计算不同的已识别用户的数量。
我尝试了以下操作,但当我按小时(日期)对它们进行分组时,它无法保留之前输入的所有 ID 的记录。
COUNT( distinct (case when userId <> 1000 then userId end)) as numSELFIDUsers
对于输出,我想要类似的东西:
+------------+-------------+----------------------+
| Date | HourOfDay | numSELFIDUsers |
+------------+-------------+----------------------+
| 2014-08-27 | 13 | 2 |
+------------+-------------+----------------------+
| 2014-08-27 | 14 | 0 |
+------------+-------------+----------------------+
| 2014-08-27 | 17 | 0 |
+------------+-------------+----------------------+
如果有任何问题,请告诉我。 预先感谢您的帮助。
最佳答案
我想你想要这样的东西:
select date(time), hour(time),
COUNT(distinct case when userId <> 1000 then userId end) as numSELFIDUsers
from usercarts
where date(time) = '2014-08-27'
group by date(time), hour(time)
order by 1, 2;
这看起来与您在查询中的内容类似。我不确定为什么你的版本不起作用。
编辑:
您似乎还想要计数为 0 的时间。这有点具有挑战性,但您可以这样做:
select d.dt, h.hr, COUNT(distinct case when userId <> 1000 then userId end)
from (select distinct date(time) dt from usercarts where dt IN YOUR RANGE) d cross join
(select 0 as hr union all select 1 union all select 2 union all select 3 union all . . .
select 23
) h left join
usercart uc
on date(uc.time) = d.dt and hour(uc.time) = h.hr;
。 。 .
是您输入 3 到 23 其余数字的位置。
编辑二:
我怀疑您实际上是在寻找用户第一次出现的情况。如果是这样,请尝试以下操作:
select date(firsttime), hour(firsttime), count(*) as NumFirstUsers
from (select userId, min(time) as firsttime
from usercarts
where userid <> 1000
group by userId
) u
group by date(firsttime), hour(firsttime)
order by 1, 2;
关于MySQL 计数该值是否之前没有出现过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25752954/