0

我想写一个查询,显示一个成员租用的电影数量最多以及该成员的姓名。为输出列指定一个有意义的名称,例如 MAXIMUM NUMBER。

这就是我所拥有的。

select max(maximum_movies)
  from (select count(*)maximum_movies
        from mm_member join mm_rental on
        mm_rental.member_id = mm_member.member_id
        group by first, last);

我得到了最大数量,但输出应该是这样的。

First  Last  Maximum_movies
John   Doe   4

但输出是

Maximum_movies
4

有什么建议么?

4

4 回答 4

1

您可以通过这种方式使用分析排名小提琴演示

select memberid,
       last,
       first,
       rental_count
from (
select m.mm_memberid memberid,
       m.mm_last     last,
       m.mm_first    first,
       count(*) rental_count,
       rank() over (order by count(*) desc ) as count_ranking
from mm_member m
inner join mm_rental r on m.mm_memberid=r.mm_memberid
group by m.mm_memberid,
         m.mm_last,
         m.mm_first
  )
where count_ranking=1
于 2013-11-04T05:06:25.827 回答
0

用这个 :

select first,last, maximum_movies 
from mm_member join mm_rental on
        mm_rental.member_id = mm_member.member_id group by first, last where 
maximum_movies = (select max(maximum_movies) from (select count(*)maximum_movies
        from mm_member join mm_rental on
        mm_rental.member_id = mm_member.member_id group by first, last));
于 2013-11-04T04:08:11.793 回答
0

像这样的东西:

WITH CTE_CNT AS ( 
    SELECT first, last, COUNT(*) num
    FROM 
        mm_member 
            JOIN mm_rental ON mm_rental.member_id = mm_member.member_id
    GROUP BY first, last
),
SELECT cnt.first, cnt.last, maxrent.mx
FROM (
    SELECT MAX(num) as mx FROM CTE_CNT
    ) maxrent JOIN CTE_CNT AS cnt ON cnt.num = maxrent.mx
;
于 2013-11-04T04:04:38.073 回答
-1

您只需 1 步即可进行选择。它实际上并不是您要查找的 MAX,而只是连接表的 COUNT。

    SELECT TOP 1
    M.member_id
    , M.first
    , M.last
    , COUNT(R.*) MovieCount
    FROM mm_member M 
    JOIN mm_rental R ON  R.member_id = M.member_id
    GROUP BY M.member_id, M.first, M.last
    ORDER BY MovieCount DESC
于 2013-11-04T05:19:45.420 回答