查询返回相同的总和 - oracle sql
Posted
技术标签:
【中文标题】查询返回相同的总和 - oracle sql【英文标题】:Query returning same sums - oracle sql 【发布时间】:2009-05-04 12:59:02 【问题描述】:想知道是否有人可以了解我正在使用的 sql 查询;
我已经建立了这个查询;
SELECT SUM(TICKET_TYPE.PRICE) AS TOTALCINEMASALES, CINEMA.LOCATION, PERFORMANCE.PERFORMANCE_DATE
FROM RESERVATION, TICKET, TICKET_TYPE, CINEMA, PERFORMANCE
WHERE TICKET_TYPE.TICKET_TYPE_ID = TICKET.TICKET_TYPE_ID
AND TICKET.RESERVATION_ID = RESERVATION.RESERVATION_ID
AND RESERVATION.PERFORMANCE_ID = PERFORMANCE.PERFORMANCE_ID
AND CINEMA.LOCATION = 'SKIPTON'
AND PERFORMANCE.PERFORMANCE_DATE BETWEEN to_date('01/03/2009','DD/MM/yyyy') AND to_date('07/04/2009','DD/MM/yyyy')
GROUP BY
CINEMA.LOCATION, PERFORMANCE.PERFORMANCE_DATE
ORDER BY
TOTALCINEMASALES;
每次我运行它时,它都会在每行上为 totalcinemasales 返回一组总和,但我知道数据库中有不同级别的门票销售等,它对我更改的每个位置都执行此操作,任何指针为我该如何改进它?
谢谢
【问题讨论】:
【参考方案1】:你忘了加入 CINEMA,可能是 PERFORMANCE。
猜测:
AND CINEMA.CINEMA_ID = PERFORMANCE.CINEMA_ID
你可以使用 ANSI 连接,当你习惯它时,它实际上更容易阅读:
SELECT SUM(TICKET_TYPE.PRICE) AS TOTALCINEMASALES, CINEMA.LOCATION, PERFORMANCE.PERFORMANCE_DATE
FROM
TICKET
inner join TICKET_TYPE
on TICKET_TYPE.TICKET_TYPE_ID = TICKET.TICKET_TYPE_ID
inner join RESERVATION
on TICKET.RESERVATION_ID = RESERVATION.RESERVATION_ID
inner join PERFORMANCE
on RESERVATION.PERFORMANCE_ID = PERFORMANCE.PERFORMANCE_ID
inner join CINEMA /* the missing link */
on CINEMA.CINEMA_ID = PERFORMANCE.CINEMA_ID
WHERE
CINEMA.LOCATION = 'SKIPTON'
AND PERFORMANCE.PERFORMANCE_DATE BETWEEN to_date('01/03/2009','DD/MM/yyyy') AND to_date('07/04/2009','DD/MM/yyyy')
GROUP BY
CINEMA.LOCATION, PERFORMANCE.PERFORMANCE_DATE
ORDER BY
TOTALCINEMASALES;
【讨论】:
谢谢,你看不到的是(可能是看了你的建议后出现问题的原因)是没有从表演到电影的直接链接,我用过cinema>screen(cinema_id) >run(screen_id>>performance(run_id) - 我应该包括这两个表并为链接添加“和”吗?还是 ansi 连接,尽管我觉得我需要更多地听到我的声音。 是的,你需要加入所有的表。如果不这样做,您将获得笛卡尔积,这意味着返回 Cinema 和连接的其他表的所有组合。要了解我的意思,请从 select 子句中删除 group by 子句和 SUM。使用过滤器,您可以删除所有无用的组合。【参考方案2】:SELECT SUM(TICKET_TYPE.PRICE) AS TOTALCINEMASALES, CINEMA.LOCATION, PERFORMANCE.PERFORMANCE_DATE
FROM RESERVATION, TICKET, TICKET_TYPE, CINEMA, PERFORMANCE
WHERE TICKET_TYPE.TICKET_TYPE_ID = TICKET.TICKET_TYPE_ID
AND TICKET.RESERVATION_ID = RESERVATION.RESERVATION_ID
AND RESERVATION.PERFORMANCE_ID = PERFORMANCE.PERFORMANCE_ID
AND CINEMA.LOCATION = 'SKIPTON'
-- Added this
AND PERFORMANCE.CINEMA_ID = CINEMA.CINEMA_ID
--
AND PERFORMANCE.PERFORMANCE_DATE BETWEEN to_date('01/03/2009','DD/MM/yyyy') AND to_date('07/04/2009','DD/MM/yyyy')
GROUP BY
CINEMA.LOCATION, PERFORMANCE.PERFORMANCE_DATE
ORDER BY
TOTALCINEMASALES;
【讨论】:
以上是关于查询返回相同的总和 - oracle sql的主要内容,如果未能解决你的问题,请参考以下文章
如果行中的初始值在 SQL 中为 < 或 > 0,如何返回单独的列总和
sql server和oracle中查询结果返回指定行数的语句
如何在 Oracle 中查找 SQL 查询中返回的记录的内存大小?