给出一个保存用户状态历史记录的表:
<表类>
ID
USERID
修改
状态
tbody><<tr>1 1 01.01.2020 的 21 01.07.2020 活动 3 2 04.08.2020 活动 42 04.06.2020 活动 52 01.08.2020 的 62 01.10.2020 活动 73 01.09.2020 的 表类>
您可以使用row_number()
来获取该日期的最后状态:
select count(*)
from (select t.*,
row_number() over (partition by userid order by modified desc) as seqnum
from my_table t
where t.modified <= date '2020-07-01'
) t
where seqnum = 1 and status = 'Active';
另一个选项是关联子查询:
select count(*)
from my_table t
where t.modified = (select max(t2.modified)
from my_table t2
where t2.userid = t.userid and
t2.modified <= date '2020-07-01'
) and
t.status = 'Active';
或者,您可以使用两个级别的聚合:
select count(*)
from (select userid,
max(status) keep (dense_rank first order by modified desc) as status
from my_table t
where t.modified <= date '2020-07-01'
group by userid
) t
where status = 'Active';
由于您正在查找与提供的日期最接近的活动用户计数,因此以下操作可以工作。
select count(distinct userid)
from table
where modified <= '01.07.2020'
and status='Active'