尝试使用连接查找总计(总和)时出现sql错误

时间:2017-03-25 13:03:39

标签: sql oracle

SQL> SELECT CUSTOMER.CUSTOMERID,
  2    CUSTOMER.CUSTOMERNAME,
  3    CONCERTS.TYPEOFCONCERT
  4    SUM (CUSTOMERID) AS CUSTOMERCOUNT,
  5    DISTINCT (TYPEOFCONCERT)
  6    FROM CUSTOMER
  7    INNER JOIN BOOKING
  8    ON BOOKING.CUSTOMERID = CUSTOMER.CUSTOMERID
  9    INNER JOIN EVENT
 10    ON EVENT.EVENTID=BOOKING.EVENTID
 11    INNER JOIN CONCERTS
 12    ON CONCERTS.CONCERTID=EVENT.CONCERTID;
  SUM (CUSTOMERID) AS CUSTOMERCOUNT,
      *
ERROR at line 4:
ORA-00923: FROM keyword not found where expected

我在尝试查找参加每种类型音乐会的客户总数时遇到错误。你能告诉我出错的地方吗?

2 个答案:

答案 0 :(得分:0)

如果我理解你想做什么,你想要COUNT()客户并计算不同类型的音乐会。您还需要GROUP BY

SELECT c.CUSTOMERID, c.CUSTOMERNAME, co.TYPEOFCONCERT,
       COUNT(CUSTOMERID) AS CUSTOMERCOUNT,
       COUNT(DISTINCT TYPEOFCONCERT)
FROM CUSTOMER c INNER JOIN
     BOOKING b
     ON b.CUSTOMERID = c.CUSTOMERID INNER JOIN
     EVENT e
     ON e.EVENTID = b.EVENTID INNER JOIN
     CONCERTS co
     ON co.CONCERTID = e.CONCERTID
GROUP BY c.CUSTOMERID, c.CUSTOMERNAME, co.TYPEOFCONCERT;

编辑:

对于参加每种类型音乐会的总人数,您可以大大简化查询:

SELECT co.TYPEOFCONCERT,
       COUNT(DISTINCT b.CUSTOMERID) as num_different_customers,
       COUNT(*) as num_bookings
FROM BOOKING b INNER JOIN
     EVENT e
     ON e.EVENTID = b.EVENTID INNER JOIN
     CONCERTS co
     ON co.CONCERTID = e.CONCERTID
GROUP BY co.TYPEOFCONCERT;

注意:

  • 表别名使查询更易于编写和阅读。
  • 不需要Customer表,因为客户ID位于BOOKING
  • 目前尚不清楚您是否需要COUNT(DISTINCT)COUNT(*)。无论他们预订的音乐会数量多少,第一个对每种类型的客户只计算一次。

答案 1 :(得分:0)

您错误地使用SUM查找计数。请改用COUNT。此外,在使用聚合时使用正确的group by子句。 DISTINCT不是函数。它返回所选列/表达式值的唯一组合。使用别名可以简化查询。

  

参加各类演唱会的客户总数

所以,你想要一种音乐会类型和顾客数量。如果是这样,试试这个:

select t.TYPEOFCONCERT,
    count(*) as customer_count
from CUSTOMER c
inner join BOOKING b on b.cID = c.cID
inner join EVENT e on e.eID = b.eID
inner join CONCERTS t on t.CONCERTID = e.CONCERTID
group by t.TYPEOFCONCERT;