我開始學習 sql 查詢并試圖找出一些更復雜的查詢(對我來說)。因為我有這些表和模式:
客戶(客戶 ID、姓名、地址、年齡、余額)
導演(DirectorID、DirectorName、AwardWinner)
電影(MovieID、標題、DirectorID、等級、productionStudio、格式、ProductionYear)
DirectorID FK references director
租用(CustomerID、movieID、Pickupdate、returnDate)
CustomerID FK references Customer
movieID FK references Movies
在電影架構中
format could be ‘VHS’, ‘DVD’, ‘Blue Ray’.
rating in movies could have values such as ‘PG’, ‘PG13’,’ R’… etc
ProductionStudio could have values such as ‘Universal Studio’, ‘Disney’ …etc.
在 Director 模式中
awardWining has a value of 1 if the director won an award otherwise it will be 0.
我想弄清楚如何加入他們以找出誰租了超過 3 個標題?
uj5u.com熱心網友回復:
您可以將聚合與 group by 和 having 子句一起使用
select c.CustomerID, c.name,count(title)
from Customer c inner join Rented r
on c.CustomerID=r.CustomerID
inner join Movies m
on r.movieID=m.movieID
group by c.CustomerID, c.name
having count(title)>=3
uj5u.com熱心網友回復:
select c.CustomerId
from Customer c inner join Rented r on r.CustomerId = c.CustomerId
group by c.CustomerId
having count(*) > 3; -- use count(distinct r.MovieId) if repeated rentals is a concern
你似乎不需要Movies桌子上的任何東西,所以甚至沒有理由加入。假設您這樣做了,您通常希望依靠 id 列,而不是像Title兩個不同的行實際上可能具有相同名稱的情況。
由于作業方式的原因,group by您經常使用虛擬聚合來回傳額外的詳細資訊:
select c.CustomerId. min(c.Name) as Name
from Customer c inner join Rented r on r.CustomerId = c.CustomerId
group by c.CustomerId;
另一種方法是避免聚合步驟:
select *
from Customer
where (
select count(*) from Rented r
where r.CustomerId = c.CustomerId
) > 3;
uj5u.com熱心網友回復:
使用聚合和連接
SELECT r.CustomerId FROM Rented r
join Customer c on c.CustomerId=r.CustomerId
join Movies m on r.movieID= r.movieID
GROUP BY r.CustomerId
HAVING COUNT(DISTINCT m.title) > 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432591.html
上一篇:合并具有不同結構的表
