2016-11-22 79 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