[英]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.