簡體   English   中英

SQL如何使用分組依據計算每個客戶的總行數?

[英]SQL how to count total rows for each customer with group by?

我正在為一個問題而苦苦思索:“哪個城市的客戶觀看的電影最多?(根據租借的電影數量)”。

我正在使用MySQL中的Seikila示例數據庫來執行此操作。 城市實體與租金和客戶實體沒有關系,但是有一個地址實體包含address_id,而id取決於客戶實體。 然后,地址實體具有一個名為city_id的屬性,城市實體也已獲得該屬性。 並且customer_id屬性鏈接了客戶實體和租賃實體。

另外,我必須計算每個城市中每個客戶租用的電影總數。

我只完成了連接部分(代碼已更新):

select rental_id,cust.customer_id,city.city_id,city.city from rental as r  
inner join customer as cust on r.customer_id=cust.customer_id inner join
address as a on cust.address_id=a.address_id inner join city as city on
city.city_id=a.city_id 

我意識到我應該將city_id添加到表中,所以我的問題將是:

如何計算唯一的customer_id的行數,這樣我就可以得出每個城市 (按組) 租借電影的總數

使用COUNT(*)獲取電影租借總數,然后按城市分組。

SELECT city.city, COUNT(*) AS total_rentals
FROM rental AS r
INNER JOIN customer AS cust on r.customer_id = cust.customer_id
INNER JOIN address AS a on cust.address_id = a.address_id
INNER JOIN city ON city.city_id = a.city_id
GROUP BY city.city_id
ORDER BY total_rentals DESC
LIMIT 1

如果您還想知道該城市的客戶數量,可以將COUNT(DISTINCT cust.customer_id)添加到SELECT列表中。

暫無
暫無

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

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