簡體   English   中英

SQL 如何找到哪個客戶租了最多的電影?

[英]SQL How to find which customer has rented the most films?

我正在努力解決一個問題,即哪個客戶租借的電影最多?

我正在使用 MySQL 中的 Seikila 示例數據庫執行此操作。 我有一些東西可以將我的表連接在一起並試圖給我一個計數,但我知道只是查看租賃表中的實際數據是錯誤的。 我的代碼如下

SELECT r.rental_id, cust.customer_id, count(*) as Total_Rentals
FROM rental as r
INNER JOIN customer AS cust on r.customer_id = cust.customer_id
GROUP BY cust.customer_id;

但它告訴我例如客戶 1 租了 32 部電影,我知道這是錯誤的。 我究竟做錯了什么? 由於我被要求澄清,我使用的數據庫是: https : //dev.mysql.com/doc/sakila/en/

我試圖找出哪個客戶租借了最多的電影,我不完全確定我的劇本實際上返回了什么。

從選擇列表中刪除列rental_id count(*)降序對結果進行排序以返回前1 行:

SELECT cust.customer_id, cust.name, count(*) as Total_Rentals
FROM rental as r
INNER JOIN customer AS cust on r.customer_id = cust.customer_id
GROUP BY cust.customer_id, cust.name
ORDER BY Total_Rentals DESC LIMIT 1

但是,如果您只需要客戶的 id,則不需要加入:

SELECT customer_id, count(*) as Total_Rentals
FROM rental
GROUP BY customer_id
ORDER BY Total_Rentals DESC LIMIT 1

您需要join customerrentalgroup by customer id group by (不帶rental id)並計數:

SELECT cust.customer_id, count(*) as Total_Rentals
FROM rental as r
INNER JOIN customer AS cust on r.customer_id = cust.customer_id
GROUP BY cust.customer_id;

所以這段代碼應該可以工作。 如果它不起作用,那可能意味着您有重復或其他非常規問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM