通过在SQL中使用具有多个列的计数进行查询

时间:2018-08-04 05:30:29

标签: sql

我对SQL很陌生。

我有一个电影数据库。带有下表,并列出了其列:

类别表

列-category_idnamelast_update

电影类别表

列-film idcategory idlast_update

库存表

列-inventory_idfilm_idstore_idlast_update

出租桌

列-rental_idrental_dateinventory_idcustomer_idreturn_datestaff_idlast_update

电影表

列-film_idtitle

问题/问题 我希望创建一个查询,列出每个电影,分类的电影类别以及租借频率。我希望尽可能多地使用这五个表中的数据。

我希望该表输出电影标题列,类别名称列以及出租次数。输出应该是这样的:

title              name          rental_count
Alter Victory      Animation         10
Goofy Movie        Animation         20

真的很感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

使用联接和聚合函数count

select F.title,C.name,count(rental_id) as rental_count from Rental R
    left join Inventory I on R.inventory_id=I.inventory_id
    inner join Film_Category Fc  on I.film_id=Fc.film_id
    inner join Flim F on F.film_id=Fc.film_id
    inner join Category C on Fc.category_id=C.category_id
group by F.title,C.name

答案 1 :(得分:1)

 WITH film_rents AS 
(
SELECT  I.film_id, COUNT(1) AS rental_count
FROM Inventory AS I
INNER JOIN Rental AS R ON R.inventory_id = I.inventory_id
GROUP BY I.film_id)

SELECT F.title, ISNULL(rental_count, 0 ) AS rental_count, C.name     
FROM  Film AS F 
LEFT  JOIN  film_rents AS FR ON F.film_id = FR.film_id
INNER JOIN Film_Category AS FC ON FC.film_id = F.film_id
INNER JOIN Category AS C ON C.category_id = FC.category_id

这可以满足您的要求,但是我认为您真正想要的不仅仅是此。我说这是因为您有一个连接表Film_Category,这意味着一部电影有一个或多个类别。在这种情况下,您要求的查询(以及以上查询)不会为您完成这项工作。假设您正在使用SQL‌ Server 2017,则可以使用以下命令:

WITH film_rents AS 
(
SELECT  I.film_id, COUNT(1) AS rental_count
FROM Inventory AS I
INNER JOIN Rental AS R ON R.inventory_id = I.inventory_id
GROUP BY I.film_id),

film_categories AS 
(
SELECT FC.film_id, STRING_AGG(C.name, ',') AS categories 
FROM Film_Category AS FC  
INNER JOIN Category AS C ON C.category_id = FC.category_id
GROUP BY FC.film_id
)

SELECT F.title, ISNULL(rental_count, 0 ) AS rental_count, FC.categories AS [name]    
FROM  Film AS F 
LEFT  JOIN  film_rents AS FR ON F.film_id = FR.film_id
INNER JOIN film_categories AS FC ON FC.film_id =  F.film_id