I have a table 'purchases' with 3 columns Serviceid, Date, User_id
Some data looks like this:
20 2-Jan-18 40709217
20 2-Jan-18 40709217
40 2-Jan-18 40709217
40 2-Jan-20 40709217
50 2-Jan-21 40709217
984 22-Mar-18 18246539
269 22-Mar-18 18246539
666 1-Apr-18 18246539
My query request is:
For each 'user_id', get these information:
- First 2 earliest ServiceId and Date that user purchased
- The lastest ServiceId and Date that user purchased
- Count of services that user purchased
Result table's column must follow this order: User_id, FirstServiceid, SecondServiceid, FirstServiceDate, SecondServiceDate, LastServiceid, LastServiceDate, TotalService.
Expected output:
| User_id | FirstServiceid | SecondServiceid | FirstDate | SecondDate | LastServiceid | LastDate | TotalServices |
|---|---|---|---|---|---|---|---|
| 40709217 | 20 | 40 | 2-Jan-18 | 2-Jan-20 | 50 | 2-Jan-21 | 5 |
| 18246539 | 984 | 666 | 22-Mar-18 | 1-Apr-18 | 666 | 1-Apr-18 | 3 |
My idea was to do aggregations, then join them together but I ran into this error
"Column 'purchase.Serviceid' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"
when calling the lastest Serviceid and Date:
select user_id, max(date), serviceid
from purchases
group by user_id
How to overcome this and is there a better way to aggregate lots of information without having to use JOIN?