我必须编写一个查询,该查询将计算仅包含该类型电影类型的已购买门票的数量。最后,我必须返回电影类型和为此类型购买的门票数量。我已经写了一个查询,但是我想知道它是否可以做得更短,更紧凑?
以下是数据库方案:
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
答案 0 :(得分:2)
我认为没有理由使用表格票证,因为结果不会按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 am
我不确定重复是什么意思?在表格中= details(ticketId,movieId,numOfTickets)??
我希望ticketId是唯一的,那么如何解释重复项呢?
同一票证ID是否重复打印两次?
确定重复的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