I have an SQL table contains data for the sale of some items. In fact, it has the logs of the sale of items.
For example, there is a sale that contains 2 items: Keyboard (id:1) and mouse(id:2). Buyers can make bids to each item and multiple times, like ebay. So let's assume there are 2 buyers(ids are 97 and 98) made bids a couple of times. The related data would be:
bid_id | buyer_id | item_id | amount | time |
1 | 97 | 1 | 44.26 | 2014-01-20 15:53:16 |
2 | 98 | 2 | 30.47 | 2014-01-20 15:54:52 |
3 | 97 | 2 | 40.05 | 2014-01-20 15:57:47 |
4 | 97 | 1 | 42.46 | 2014-01-20 15:58:36 |
5 | 97 | 1 | 39.99 | 2014-01-20 16:01:13 |
6 | 97 | 2 | 24.68 | 2014-01-20 16:05:35 |
7 | 98 | 2 | 28 | 2014-01-20 16:08:42 |
8 | 98 | 2 | 26.75 | 2014-01-20 16:13:23 |
In this table, I need to select data for first item offers for each user and last offers for each user.
So if I select first item offers for each user (distinct), return data should be like:
bid_id | buyer_id | item_id | amount | time |
1 | 97 | 1 | 44.26 | 2014-01-20 15:53:16 |
2 | 98 | 2 | 30.47 | 2014-01-20 15:54:52 |
3 | 97 | 2 | 40.05 | 2014-01-20 15:57:47 |
If I select last offers for each user, return should be like:
bid_id | buyer_id | item_id | amount | time |
5 | 97 | 1 | 39.99 | 2014-01-20 16:01:13 |
6 | 97 | 2 | 24.68 | 2014-01-20 16:05:35 |
8 | 98 | 2 | 26.75 | 2014-01-20 16:13:23 |
Since I have to bring each item for each user, I tried to GROUP BY for both buyer_id and item_id, then SELECT the MIN value of time or bid_id. But It always returned me first bid_id but latest amount rows (which are last offers actually).
Here's the query I tried:
SELECT MIN(`bid_id`) AS `bid_id`,`buyer_id`,`item_id`,`amount`,`time` FROM `offers` GROUP BY `buyer_id`,`item_id`
And the result was:
bid_id | buyer_id | item_id | amount | time |
1 | 97 | 1 | 39.99 | 2014-01-20 16:01:13 |
2 | 97 | 2 | 24.68 | 2014-01-20 16:05:35 |
3 | 98 | 2 | 26.75 | 2014-01-20 16:13:23 |
As you can see, it groups by and the IDs are correct but the rest of the row values are not.
How can I correctly SELECT first and/or last rows when grouping buy multiple columns?