简体   繁体   中英

SQL Error - not a group by expression

With this SQL Query, I am attempting to list overdue book by patron. In addition, I want to group and order the books by patron. I understand you have to use some kind of aggregate function when doing a GROUP BY function. Even so, I am getting a "not a group by expression" error. Any help is appreciated.

Edit: updated code

What if I want to get the total fees per person and book? The bottom code is still resulting in the same error.

        SELECT PATRON.LAST_NAME, PATRON.FIRST_NAME, PATRON.PHONE, BOOK.BOOK_TITLE, CHECKOUT.DUE_DATE, SUM((SYSDATE - CHECKOUT.DUE_DATE) * 1.00) AS FEE_BALANCE
FROM CHECKOUT 
JOIN PATRON 
ON CHECKOUT.PATRON_ID=PATRON.PATRON_ID 
JOIN COPY 
ON CHECKOUT.COPY_ID=COPY.COPY_ID 
JOIN BOOK
ON COPY.BOOK_ID=BOOK.BOOK_ID 
WHERE CHECKOUT.RETURN_DATE IS NULL 
AND CHECKOUT.DUE_DATE > SYSDATE
GROUP BY PATRON.PATRON_ID
HAVING SUM((SYSDATE - CHECKOUT.DUE_DATE) > 0
ORDER BY PATRON.LAST_NAME, PATRON.FIRST_NAME;

You need to add these 3 columns to the GROUP BY clause...

PATRON.PHONE, BOOK.BOOK_TITLE, CHECKOUT.DUE_DATE

So it would be...

SELECT 
  PATRON.LAST_NAME, 
  PATRON.FIRST_NAME, 
  PATRON.PHONE, 
  BOOK.BOOK_TITLE, 
  CHECKOUT.DUE_DATE, 
  SUM((SYSDATE - CHECKOUT.DUE_DATE) * 1.00) AS BALANCE
FROM CHECKOUT 
JOIN PATRON 
ON CHECKOUT.PATRON_ID=PATRON.PATRON_ID 
JOIN COPY 
ON CHECKOUT.COPY_ID=COPY.COPY_ID 
JOIN BOOK
ON COPY.BOOK_ID=BOOK.BOOK_ID 
WHERE CHECKOUT.RETURN_DATE IS NULL 
AND CHECKOUT.DUE_DATE > SYSDATE
GROUP BY PATRON.LAST_NAME, PATRON.FIRST_NAME, PATRON.PHONE, BOOK.BOOK_TITLE, CHECKOUT.DUE_DATE
ORDER BY PATRON.LAST_NAME, PATRON.FIRST_NAME

Bottom line is, if you have a GROUP BY clause, you can only select columns that are part of the GROUP BY unless you are using some kind of scalar value function on them, like COUNT, SUM, MAX, MIN, etc.

Otherwise if you aren't grouping or using a scalar-value function, multiple rows could have different values for that column, so what would the query results be?

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