简体   繁体   中英

Distinct doesn't work

The below code gives a wrong result. I am using DISTINCT command but type appears two times on the results.

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;

Results:

在此处输入图片说明

与众不同意味着该行作为一个整体不应重复,在您的情况下,该类型出现两次,但Concert_id和number_of_customers不同。

Do not use DISTINCT AND GROUP BY . GROUP BY already makes it distinct.

You need to tell us which of the rows 10001 or 10000 you want to keep. This one will keep the lowest one.

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;

You can use MIN or MAX in your WHERE clause to get your aim:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM