mysql - 按发行日期累计计数

标签 mysql

我有一个表格,显示每个日期的客户 ID 列表 - 显示在任何特定日期活跃的客户。因此每个日期都可以包含在另一个日期中也存在的 ID。

bdate            customer_id
2012-01-12       111
2012-01-13       222
2012-01-13       333
2012-01-14       111
2012-01-14       333
2012-01-14       666
2012-01-14       777

我想编写一个查询来计算两个日期之间唯一 ID 的总数 - 开始日期是行日期,结束日期是 future 的特定日期。

我的查询是这样的:

select
  bdate,
  count(distinct customer_id) as cts
from users
where bdate between bdate and current_date
group by 1
order by 1

但这会产生每个日期的唯一用户数,如下所示:

bdate            customer_id
2012-01-12       1
2012-01-13       2
2012-01-14       4

我想要的结果是(开始行日期和 2012-01-14 之间的用户数)

bdate            customer_id
2012-01-12       5  - includes (111,222,333,666,777)
2012-01-13       5  - includes (222,333,111,666,777)
2012-01-14       4  - includes (111,333,666,777)

最佳答案

@Strawberry说,你可以像这样加入:

select
    t1.bdate,
    count(distinct t2.customer_id) as cts
from users t1
join users t2 on t2.bdate >= t1.bdate
where t1.bdate between t1.bdate and current_date
group by t1.bdate
order by t1.bdate

加入 t2 可以获得特定日期和 current_date 之间的所有用户,然后 count t2 的 customer_id,就是这样。

SqlFiddle Demo Here

关于mysql - 按发行日期累计计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40731953/

相关文章:

mysql - 柴油查询中的"SOUNDS LIKE"

php - MYSQL和PHP如何在特定条件后显示数据

mysql - 处理跨临时服务器和生产服务器的 Rails 迁移的最佳方法是什么?

php - 选择 * 不同的地方

php - mysql 中按日期排序不显示今天日期的结果

mysql - 如何通过 id 查找记录并选择几列,ruby on rails?

MySQL:检索所有字段 SELECT * 当其中一个字段是二进制且需要十六进制时

php pdo从具有多个where子句的多个表中进行选择

PHP/JSON : Data from MySQL database does not appear in calendar

mysql - 无法从另一个容器访问Docker容器中的MySQL数据库