Mysql SQL中计数状态的聚合
我正在处理一些具有播放状态的日志数据,其中包括Mysql SQL中计数状态的聚合,mysql,sql,oracle,hive,Mysql,Sql,Oracle,Hive,我正在处理一些具有播放状态的日志数据,其中包括play和end。在游戏过程中,客户端会多次报告play,但当出现end时,表示游戏结束,如 user_id status timestamp a play xxx a play xxx a play xxx a end xxx b play xxx b end xxx c play xxx
play
和end
。在游戏过程中,客户端会多次报告play
,但当出现end
时,表示游戏结束,如
user_id status timestamp
a play xxx
a play xxx
a play xxx
a end xxx
b play xxx
b end xxx
c play xxx
c play xxx
c end xxx
a play xxx
a play xxx
a end xxx
a play xxx
a end xxx
现在,我可以使用row\u number()
计算user\u id
的数量,游戏的状态超过2个play
如下:
# I realize this is a wrong query...
select count(distinct user_id) as cnt_uid
(select
user_id,status,timestamp,
row_number() over (partition by user_id, status, order by timestamp) as rn
from tableA) a
where rn>=2
但是如果我需要计算超过2个play
状态的游戏数(例如:user A
有2个以上play
状态的游戏,而user C
有1个),该怎么做?感谢您的帮助
*PS:预期结果是多个游戏的状态超过2个play
,对于上面给出的数据,结果是3个您可以使用status='end'
的累计和定义“游戏”。然后进行聚合并再次聚合:
select user_id, count(*) as games_with_2+_plays
from (select user_id, grp, count(*) as num_plays
from (select t.*,
sum(case when status = 'end' then 1 else 0 end) over (partition by user_id order by timestamp) as grp
from t
) t
where status = 'play'
group by user_id, grp
)
where num_plays >= 2
group by user_id;
您可以使用DENSE_RANK()(如果在中可用)hive@DigvijayS谢谢你的回复。我在Hive
中尝试了densite\u rank()(按状态排序)
,我认为结果与user\u id
相当。。。如果我没有以正确的方式使用它,请随时告诉我……你能通过编辑你的帖子来添加预期的输出吗。嗨@DigvijayS我刚刚修改了帖子,实际上,在这种情况下预期的输出只是一个数字:3
谢谢你的精彩回答!!!在您的查询中,status='end'
被删除,这是有效的。如果我需要每个游戏的时间间隔(时间间隔=每个游戏的end
-第一次玩的时间戳),如何计算?@user2894829。您可以做一些类似于min(时间戳)
和max(时间戳)
之间的区别的事情。