简体   繁体   English

SQL查询中每个ID的MAX(COUNT(*))

[英]MAX(COUNT(*)) for each ID in a SQL query

I'm needing some help with a SQL query using PostgreSQL 9.4. 我需要有关使用PostgreSQL 9.4进行SQL查询的帮助。

I need the most rented movies on each local, this is the data I'm asked to select 我需要每个本地电影中租金最高的电影,这是我要选择的数据

  • movie title 电影标题
  • year
  • local id 本地ID
  • number of rents 房租数量

Tables: 表:

rental(idMovie, idLocal, idClient)
movies(idMovie, title, description, year)

This is what I have done, but is not what i am asked to do. 这是我所做的,但不是我被要求做的。

SELECT m.tile, m.year, r.idLocal, COUNT(*) AS cont
FROM rental r, movies m
WHERE m.idMovie=r.idMovie
GROUP BY r.idLocal, m.title, m.year
ORDER BY COUNT(*) DESC;

If I understand your question correctly what you want is to show the most rented out movie(s) for every location. 如果我正确理解了您的问题,那么您想要的是在每个地点放映最多的电影。

If that is the case then you could use a window function like rank() which will assign a ranking number to all movies based on the number of rentals for each location. 如果是这种情况,则可以使用诸如rank()类的窗口函数,该函数将根据每个位置的出租数量为所有电影分配一个排名编号。 The where clause then filters out the highest ranking movies (there can of course be more than one that shares the top spot). 然后,where子句会过滤掉排名最高的电影(当然可以有多个电影排在首位)。

select m.title, m.year, r.idLocal, r.rents
from movies m 
join (
  select 
    idMovie, 
    idlocal,
    count(idmovie) rents,
    rank() over (
      partition by idlocal 
      order by count(idmovie) desc
    ) rn
  from rental 
  group by idMovie, idLocal
) r on m.idMovie = r.idMovie 
where rn = 1
order by idlocal;

Sample SQL Fiddle 示例SQL提琴

Try this... 尝试这个...

SELECT r.idLocal, m.title, m.year, count(r.idMovie) as count_movie
FROM rental r, movies m
WHERE m.idMovie=r.idMovie
GROUP BY r.idLocal, m.title, m.year
ORDER BY count_movie DESC;

Or 要么

SELECT r.idLocal, m.title, m.year, count(r.idMovie) as count_movie
FROM rental r, movies m
WHERE m.idMovie=r.idMovie
GROUP BY r.idLocal, m.title, m.year
ORDER BY count(r.title) DESC;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM