[英]What is the best way to do this query (SQL)
我需要做一个查询,但我找不到有效的好方法。
每次客户听一首歌,都会用他的密钥和 track_id、日期注册一行。
我想检查每个客户他上个月听的曲目是否是新的(本月之前从未听过)
一行看起来像这样:
key | track_id | date
asd | 12312 | 12/02/2020
fds | 12323 | 12/05/2020
ETC
我想我可以用 window 函数做一些事情,但我似乎找不到一个好方法来做这件事。
然后我还需要从这个列表中获得前 3 名听得最多的歌曲,我猜我可以用 window function 来完成。
如果有人可以帮助我? 非常感谢。
使用聚合和 window 函数:
select key, count(*) as num_rows,
count(*) as num_tracks,
sum( case when first_yyyymm = yyyymm then 1 else 0 end) as num_new_tracks,
sum( case when first_yyyymm < yyyymm then 1 else 0 end) as num_prev_tracks
from (select t.key, track_id, date_trunc('month', date) as yyyymm,
min(date_trunc('month', date) ) over (partition by key, track_id) as first_yyyymm
from t
group by key, track_id, yyyymm
) t
where yyyymm >= date_trunc('month', current_date)
group by key
一条建议。 如果您需要他人的帮助,请始终包含示例数据集的 DDL。 期望人们为你做这件事是不公平的。 (在这种情况下我做到了)
create table sandbox.songs
(key varchar,
track_id number,
dt date);
insert into sandbox.songs
values
('asd', 12312, '12/02/2020'),
('fds', 12323, '12/05/2020'),
('asd', 11000, '04/05/2020'),
('fds', 92823, '04/07/2020'),
('asd', 11000, '3/05/2020'),
('fds', 12323, '12/05/2020'),
('asd', 92834, '3/05/2020');
问题 1
select
key,
count(0),
sum(case when dt < current_date - 30 then 1 else 0 end) as older_than_30,
sum(case when dt >= current_date - 30 then 1 else 0 end) as within_30
from sandbox.songs group by key;
[在此处输入图片描述][1]
问题2
track_id,
count(0)
from sandbox.songs
group by track_id
order by count(0) desc
limit 3;
[enter image description here][2]
[1]: https://i.stack.imgur.com/CeDqw.png
[2]: https://i.stack.imgur.com/sdKV0.png
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.