-2

I have below columns in book_history table. Every new book taken will have entry in this table with a new auto increment id, current date, student id and book id.

Id, RecordCreatdOn, StudentId, BookId

I want to get students (studentId) who have last taken any book before '2017-12-31'. Can anyone help me with the query to fetch the same ?

Strawberry
  • 33,750
  • 13
  • 40
  • 57
Lin toka
  • 15
  • 5

3 Answers3

3

You need to group by the student to get every students last book with max(RecordCreatdOn)

select studentId
from book_history
group by studentId
having max(RecordCreatdOn) < '2017-12-31'
juergen d
  • 201,996
  • 37
  • 293
  • 362
0

That is straight forward:

 Select Distinct StudentID from book_history where 
    RecordCreatedOn < @yourDate
Hussein Salman
  • 7,806
  • 15
  • 60
  • 98
  • This won't work - if a user checked out a book before and after `@yourDate` they would be returned by this – Aaron Dietz Mar 22 '18 at 15:59
  • He need students who have took any book before a specific date. Didn't understand why it wouldn't work – Hussein Salman Mar 22 '18 at 16:01
  • This part `who have last taken any book before '2017-12-31'` implies they also haven't taken a book since then. I missed it too at first, almost posted the same answer – Aaron Dietz Mar 22 '18 at 16:30
0

If you google 'mysql date comparisons', you'll get a LOT of Stackoverflow examples. Look at answers such as: mysql date comparison with date_format

That can give you at least somewhere to start.

Try this query:

Select StudentId from book_history
WHERE DATE(RecordCreatdOn) <= '2017-12-31'
cbloss793
  • 1,555
  • 4
  • 19
  • 30