I have an ActiveRecord model SentimentRecords with table sentiment\_records where each record has attributes: user\_id, sentiment\_id,lecture\_id, and timestamp.
My Query: Given a LECTURE\_ID, and a DATETIME, for each sentiment\_id, I want a count of how many user\_id's (users) recorded each sentiment\_id; for each user\_id only counting the latest timestamp <= the given datetime.

Here is a formulation that isn't working: 

```
SentimentRecords.find_by_sql
("SELECT sentiment_id,count(*) 
FROM sentiment_records WHERE id          
IN (SELECT max(id) FROM sentiment_records 
WHERE lecture_id=LECTURE_ID GROUP BY user_id 
WHERE timestamp <= DATETIME) GROUP BY sentiment_id")

```