2016-11-22 85 views
3

我有一张表格,显示每个日期的客户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的两个日期之间的总数查询 - 起始日期是行日期和结束日期在未来的某个特定日期。

我的查询看起来是这样的:

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) 
+0

看看你能不能让你一个加入工作 – Strawberry

+0

你能详细点吗? – user2022284

回答

0

@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

+0

嗨 - 查询的作品,但对我来说是超时。用户表格相当庞大。还有另一种更有效运行的方法吗? – user2022284

+0

@ user2022284,试着让特定的日子成为明确的日期,我想如果有大量的数据,不管它是什么样的解决方案,如果你想更有效率,你应该为你的表做一些优化,因为这里是一个'加入'解决方案,如果有另一个解决方案,它可能或应该是子查询解决方案,那么你也将面临性能问题,因为你有一个巨大的数据。 ^^ – Blank