繁体   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