如何选择日期列表之间的时间范围?

时间:2017-08-31 03:01:10

标签: mysql sql

有一个名为"记录"。

的表格
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

我想要算一次,有人可以帮我这个吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;