1

I recently completed the SQLmodel documentation, but it doesn't tell me how to use the group_by command. I am trying the following:

SELECT reader_status, count(book_id) 
FROM readerbook
WHERE reader_id=1
GROUP BY reader_id, reader_status

to be used in the SQLmodel code.

statement = select(
    ReaderBook.reader_status, func.count(ReaderBook.book_id).label("count")
)

This is my code. How do I use the group_by "reader_id" condition ?

noninertialframe
  • 568
  • 1
  • 10
  • 24
  • Does this answer your question? [Group by & count function in sqlalchemy](https://stackoverflow.com/questions/1052148/group-by-count-function-in-sqlalchemy) – noninertialframe Oct 15 '21 at 15:02
  • Thank you! I tried using this but the group_by doesn't work. I imported the func from sqlalchemy, everything else seems to work except for group_by Do I have to import something else ? – Shivam Sharma Oct 16 '21 at 07:26

1 Answers1

1

Let's say readerBook is the variable of the table i.e.

readerBook = Table(
   ...
)

Then you can try the following.

statement = select([
    readerBook.c.reader_status, func.count(readerBook.c.book_id).label("count")
])
.select_from(readerBook)
.group_by(readerBook.c.reader_id)
Nimantha
  • 6,405
  • 6
  • 28
  • 69
noninertialframe
  • 568
  • 1
  • 10
  • 24