明显不起作用

时间:2014-04-06 12:08:43

标签: sql oracle oracle-sqldeveloper database

以下代码给出了错误的结果。我正在使用DISTINCT命令,但类型在结果上出现两次。

SELECT DISTINCT 
    CONCERT.CONCERT_ID, CONCERT.C_TYPE,  
    COUNT(BOOKINGS.CUSTOMER_CUSTOMER_ID) AS NUMBER_OF_CUSTOMERS
FROM 
    CONCERT, CUSTOMER, EVENT, BOOKINGS
WHERE 
    CUSTOMER.CUSTOMER_ID =  BOOKINGS.CUSTOMER_CUSTOMER_ID
    AND EVENT.EVENT_ID =  BOOKINGS.EVENT_EVENT_ID
    AND CONCERT.CONCERT_ID =  EVENT.CONCERT_ID
GROUP BY 
    CONCERT.CONCERT_ID, CONCERT.C_TYPE
ORDER BY 
    CONCERT.CONCERT_ID DESC;

结果:

enter image description here

3 个答案:

答案 0 :(得分:6)

distinct意味着整个行不应该重复,在您的情况下,类型会出现两次但是与concert_id和number_of_customers不同。

答案 1 :(得分:1)

请勿使用DISTINCT AND GROUP BYGROUP BY已经使它与众不同。

您需要告诉我们您要保留哪一行10001或10000。这个将保持最低的一个。

SELECT MAX(CONCERT.CONCERT_ID)  CONCERT_ID, CONCERT.C_TYPE,  
COUNT(BOOKINGS.CUSTOMER_CUSTOMER_ID) AS NUMBER_OF_CUSTOMERS
FROM CONCERT, CUSTOMER, EVENT, BOOKINGS
WHERE CUSTOMER.CUSTOMER_ID =  BOOKINGS.CUSTOMER_CUSTOMER_ID
AND EVENT.EVENT_ID =  BOOKINGS.EVENT_EVENT_ID
AND CONCERT.CONCERT_ID =  EVENT.CONCERT_ID
GROUP BY CONCERT.C_TYPE
ORDER BY CONCERT.CONCERT_ID DESC;

答案 2 :(得分:0)

您可以在MIN条款中使用MAXWHERE来实现目标:

SELECT DISTINCT COURSE.COURSE_ID, COURSE.TITLE, 
COUNT(ATTENDANCE.STUDENT_ID) AS NUMBER_OF_STUDENTS
FROM ATTENDANCE, OFFERING, COURSE, STUDENT
WHERE OFFERING.OFFERING_ID = ATTENDANCE.OFFERING_ID
AND OFFERING.COURSE_ID = COURSE.COURSE_ID
AND STUDENT.STUDENT_ID = ATTENDANCE.STUDENT_ID
AND COURSE.COURSE_ID IN (SELECT MAX(t1.COURSE_ID) FROM COURSE t1 GROUP BY t1.TITLE)
GROUP BY COURSE.COURSE_ID, COURSE.TITLE
ORDER BY COURSE_ID DESC;