我必须编写一个查询来计算购买的门票数量,该门票仅包含该类型的电影类型。最后,我必须返回电影类型和为该类型购买的门票数量。我写了一个查询,但我想知道它是否可以缩短和更紧凑?
以下是数据库架构:
movies(movieId, movieGenre, moviePrice)
tickets(ticketId, ticketDate, customerId)
details(ticketId, movieId, numOfTickets)
这是我的查询:
select m.genre, count(*)
from(select t.ticketId, m.genre
from(select d.ticketId
from(select m.genre, t.ticketId
from tickets t join details d on t.ticketId =
d.ticketId join movies m on d.movieId = m.movieId
group by m.genre, t.ticketId) d
group by d.ticketId
having count(*) = 1) as t join details d on t.ticketId =
d.ticketId join movies m on d.movieId = m.movieId
group by t.ticketId, m.genre) m
group by m.genre;
这在数据库上运行,所以我只能发布示例输出:
comedy 29821
action 27857
rom-com 19663
我认为没有理由使用表票证,因为结果不会被ticketDate或customerID过滤或聚合。因此,更短的sql是
SELECT m.moviegenre,
Sum(d.numoftickets) as SumNum
FROM details d
LEFT JOIN movies m
ON d.movieid = m.movieid
GROUP BY m.moviegenre
HAVING SumNum > 0
ORDER BY m.moviegenre
上午3点28分
我不确定Duplicates是什么意思?在table = details(ticketId,movieId,numOfTickets)?? 我希望ticketId是唯一的,那么什么可以解释重复? 同一张票是否被打印两次,反复?
确定重复的ticketId数量 -
SELECT ticketId, count(*) as cnt
FROM details d
GROUP By ticketId
HAVING count(*) > 1
确定重复的“细节”行数 -
SELECT ticketId, movieId, numOfTickets, count(*) as cnt
FROM details d
GROUP By ticketId, movieId, numOfTickets
HAVING count(*) > 1
然后,它可能是表=电影(movieId,movieGenre,moviePrice)是重复的?确定movieId的重复数量 -
SELECT movieId, count(*) as cnt
FROM movies m
GROUP BY movieId
HAVING count(*) > 1
从细节中删除重复项 -
SELECT m.moviegenre,
Sum(d.numoftickets) as SumNum
FROM
(Select Distinct * From details) d
LEFT JOIN movies m
ON d.movieid = m.movieid
GROUP BY m.moviegenre
ORDER BY m.moviegenre