我必须实施
创建一个视图,显示数据库中每部电影的总租金收入
所以我做了
NULL
交易表有:transaction_id,movie_copy_id,customer_id,price。
MOVIE_COPIES表有:type,store_id,movie_copy_id,movie_number
电影表有:id,name,minutes。
但甲骨文让我失望
CREATE OR REPLACE VIEW MovieIncome AS SELECT s.movie_copy_id, SUM(S.PRICE)
AS Income FROM TRANSACTIONS s
left OUTER JOIN MOVIE_COPIES ON MOVIE_COPIES.movie_copy_id = s.movie_copy_id
left OUTER JOIN MOVIES ON MOVIES.ID = MOVIE_COPIES.MOVIE_copy_id
WHERE MOVIES.ID = MOVIE_COPIES.MOVIE_copy_id
GROUP BY MOVIES.NAME;
我的朋友有同样的任务,他的专栏名称不同,但目的相同,工作正常,对我来说没有。
答案 0 :(得分:0)
我能看到的问题是:
movies
和movie_copies
表之间的联接可能应该在movies.id = movie_copies.movie_number
上(这只是猜测)。此代码有效:
CREATE OR REPLACE VIEW MovieIncome AS
SELECT s.movie_copy_id, MOVIES.NAME, SUM(S.PRICE) AS Income
FROM TRANSACTIONS s
LEFT OUTER JOIN MOVIE_COPIES ON MOVIE_COPIES.movie_copy_id = s.movie_copy_id
LEFT OUTER JOIN MOVIES ON MOVIES.ID = MOVIE_COPIES.movie_number
GROUP BY s.movie_copy_id, MOVIES.NAME;
Sample SQL Fiddle显示它的实际效果。
也许查询应该使用movies表作为源,然后左连接其他表或者可能使用内连接,因为应该可以安全地假设事务表中的任何行必须与movie_copies表有关系
所以也许你想要的是这样的:
CREATE OR REPLACE VIEW MovieIncome AS
SELECT MOVIE_COPIES.movie_copy_id, MOVIES.NAME, COALESCE(SUM(S.PRICE),0) AS Income
FROM MOVIES
LEFT OUTER JOIN MOVIE_COPIES ON MOVIES.ID = MOVIE_COPIES.movie_number
LEFT OUTER JOIN TRANSACTIONS s ON MOVIE_COPIES.movie_copy_id = s.movie_copy_id
GROUP BY MOVIE_COPIES.movie_copy_id, MOVIES.NAME;
对于没有租借任何副本的电影,这将返回0。