按年度选择最小计数('x')
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了按年度选择最小计数('x')相关的知识,希望对你有一定的参考价值。
我正在尝试创建一个表格,显示每年播放次数最少的歌曲。
例如,如果Song1和Song2都只有1次播放而Song3在2018年有2次播放而且Song1在2017年有1次播放而Song2在2017年有2次播放,我想要一个可以返回3行的表:
Song1 - 2018 - 1次播放
Song2 - 2018 - 1次播放
Song1 - 2017 - 1次发挥
有没有办法显示min(count('x'))= count('x')的歌曲。我敢肯定这不是正确的语法,但它本质上是我想要找到的。
SELECT * FROM music
NATURAL JOIN (SELECT extract(year from date) AS yr, song_code, COUNT('x')
FROM singles NATURAL JOIN plays
GROUP BY extract(year from date), song_code
ORDER BY yr desc, COUNT('x') desc);
目前我有按年份播放次数分组的歌曲,但我不确定如何只播放播放次数最少的歌曲。
答案
这应该工作。这也是为什么我们应该使用WITH(子查询因子分解)而不是内联视图的一个很好的例子。使用year,song_code和count创建一个song_count子查询。
另外,为了清楚起见,我会明确定义连接
WITH song_count as
SELECT extract(year from date) AS song_year, song_code, count(*) as play_count
FROM singles NATURAL JOIN plays
group by extract(year from date),song_code
select * from song_count
where
(song_year,play_count) in (select song_year,min(play_count) from song_count group by song_year)
另一答案
- 您可以更喜欢使用分析函数,例如dense_rank()
而不是连接或子查询。
with songs( id, year, play_id ) as
(
select 1, 2018, 1 from dual union all
select 2, 2018, 1 from dual union all
select 3, 2018, 1 from dual union all
select 3, 2018, 2 from dual union all
select 1, 2017, 1 from dual union all
select 2, 2017, 1 from dual union all
select 2, 2017, 2 from dual
)
select id, year, play_cnt
from
(select s.*, dense_rank() over (partition by year order by play_cnt) dr
from
(select id, year, count(play_id) as play_cnt
from songs s
group by id, year
) s
)
where dr = 1;
ID YEAR PLAY_CNT
---------- ---------- ----------
1 2017 1
2 2018 1
1 2018 1
另一答案
你可以尝试使用row_number():
SELECT *
FROM music
NATURAL JOIN
(select yr, song_code, play_count
from
(SELECT extract(year from date) AS yr, song_code, COUNT('x') play_count, row_number() over (partition by extract(year from date), song_code order by COUNT('x')) rn
FROM singles NATURAL JOIN plays
GROUP BY extract(year from date), song_code
)
where rn = 1;
以上是关于按年度选择最小计数('x')的主要内容,如果未能解决你的问题,请参考以下文章