假设有一个表 action
可以跟踪功能是打开还是关闭。这些字段为 user_id
, status
(" on"或" off), date
和 time
。
此外,还有一个表 user_status
,用于保存有关用户的历史数据。字段为 user_id
, status
, date
和 time
。
问题即可。今天有多少用户使用此功能?有多少用户打开了此功能?如何将当前数据添加到历史数据?
给出的答案如下:
select count(distinct(user_id)) from action
where status = "on" and date = today()
但似乎这也包括那些已经拥有自己身份的人#34;"前一天。
另一个答案是:
create table total as
( select us.user_id, today(), us.status
from
(select user_id, status, date
from user_status
where date = today()-1) us
left outer join
(select user_id, status, date, max(time)
from action
where date = today()
group by user_id, status) ts on us.user_id = ts.user_id
where ts.user_id is null
union all
select user_id, today(), status
from
(select user_id,status, max(time)
from action
where date = today()
group by user_id, status) a
union all
select * from user_status )
这似乎解释了与昨天具有相同状态的用户和昨天有不同操作的用户?这基本上会将今天的数据添加到历史数据中吗?然后你可以回答前两个问题:
select count(distinct(user_id)) from total
where status = "on" and date = today()
select count(distinct(user_id)) from total
where status = "on"
这是正确的吗?
答案 0 :(得分:0)
select
count(distinct (case when status="on" and date=today() then user_id else null end)) as current,
count(distinct (case when status="on" and date<today() then user_id else null end)) as previous
from action