MySQL 计数该值是否之前没有出现过

标签 mysql sql count distinct-values

这是一个包含用户、购物车时间的表格。 一个用户可以拥有多个购物车。所有匿名用户都有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/

相关文章:

MySQL 无需对整个数据集进行排序即可按热度排名前 10

php - 创建个人 MySQL 数据库

mysql - 使用同一表的另一列的值分组插入到列中

algorithm - 概率算法 : Finding probable correct item in a list (e. g John, John, Jon)

mysql - 我想要一个从我的数据库中删除重复条目的查询

mysql - 如何在mysql中获取我的表中的最大且不重复的数据?

Mysql 检查时间之间的可用性

如果在 WHERE 子句中使用函数,sql 查询时间从 1 秒跳到 1 分钟以上

sql - 可以使用 SQL 将报告分组在一起吗?

Java 计算字母、数字和符号