我正在编写一个查询,该查询计算每年的某天活跃18个月的人数。
我遇到的问题是,各年之间存在时间重叠,这导致后几年被低估,因为它们被归类为上一年。
例如,“ 2017-03-06”可以被视为2018年和2017年的活动。 这是我的查询:
select case when deposit_dt between '2017-02-07' and date then '2018'
when deposit_dt between '2016-02-07' and '2017-08-07' then '2017'
when deposit_dt between '2015-02-07' and '2016-08-07' then '2016'
when deposit_dt between '2014-02-07' and '2015-08-07' then '2015'
when deposit_dt between '2013-02-07' and '2014-08-07' then '2014'
end as yr, count(unique(op_id))
from activity_table
where deposit_dt between '2013-02-07' and date
group by deposit_dt
关于如何解决此问题的任何建议(除了每年运行一次新查询)?
答案 0 :(得分:1)
我的感觉是,您确实需要遵循以下几点:
select
count(case when deposit_dt between '2017-02-07' and date then 1 end) as 2018,
count(case when deposit_dt between '2016-02-07' and '2017-08-07' then 1 end) as 2017,
count(case when deposit_dt between '2015-02-07' and '2016-08-07' then 1 end) as 2016,
count(case when deposit_dt between '2014-02-07' and '2015-08-07' then 1 end) as 2015,
count(case when deposit_dt between '2013-02-07' and '2014-08-07' then 1 end) as 2014
from activity_table
where deposit_dt between '2013-02-07' and date;
请注意,按deposit_dt
分组是没有意义的,因为这是用于汇总的列。
这假设您没有足够的逻辑来考虑可能重叠的日期。如果您可以提供逻辑方法来解决与多个范围相匹配的日期,则可以更新上述查询。
答案 1 :(得分:0)
我认为这可能是您想要的。
select count(distinct [2018Users]) as [2018], count(distinct [2017Users]) as [2017],count(distinct [2016Users]) as [2016]
from(
select case when deposit_dt between '2017-02-07' and date then op_id end as [2018Users],
case when deposit_dt between '2016-02-07' and '2017-08-07' then op_id end as [2017Users],
case when deposit_dt between '2015-02-07' and '2016-08-07' then op_id end as [2016Users]
from activity_table
) c