2017-08-31 91 views
0

有一個名爲「記錄」的表。如何選擇日期列表中的時間範圍?

userid | date 
------ | ------ 
1  | 2017-08-21 
1  | 2017-08-22 
2  | 2017-08-22 
1  | 2017-08-23 
3  | 2017-08-23 

現在我需要三個SQL來計算用戶ID。

select count(DISTINCT userid) from record where date between 2017-08-21 and 2017-08-23; 

結果:3

select count(DISTINCT userid) from record where date between 2017-08-22 and 2017-08-23; 

結果:3

select count(DISTINCT userid) from record where date between 2017-08-23 and 2017-08-23; 

結果:2

我想指望那些由一個時間,可能有人能幫我解決這個好嗎?

+0

我不明白。你試圖得到什麼結果? – Barmar

+0

不知道你在問什麼。 「我想要數一次」是什麼意思? – Chiperific

回答

0
SELECT distinct date_field, 
     (select count(distinct userid) from record r1 where r1.date_field between r2.date_field and '2017-08-23') 
    FROM record r2 

或者這更有效的版本由謝爾登建議

SELECT date_field, 
     (select count(distinct userid) from record r1 where r1.date_field between r2.date_field and '2017-08-23') 
    FROM (select distinct date_field from record) r2 
+0

... FROM(SELECT distinct date_field FROM record)r2;更高效 –

+0

好點@謝爾登。陳 – davidwebster48

0

使用條件彙總:

select count(distinct case when between '2017-08-21' and '2017-08-23' then userid end), 
     count(distinct case when between '2017-08-22' and '2017-08-23' then userid end), 
     count(distinct case when between '2017-08-24' and '2017-08-23' then userid end) 
from record r; 
相關問題