简体   繁体   中英

get last record per category filter by date

I have this tables SQL Fiddle

items table:

+----+----------+
| id |   name   |
+----+----------+
|  1 | Facebook |
|  2 | Twitter  |
|  3 | Amazon   |
+----+----------+

prices table:

+----+-----------+---------+-----------------------------+
| id |    buy    | item_id |             created_at      |
+----+-----------+---------+-----------------------------+
|  1 |   43000   |    1    | June, 18 2014 17:31:04+0000 |
|  2 |   44000   |    1    | June, 19 2014 17:31:04+0000 |
|  3 |   30000   |    2    | June, 20 2014 17:31:04+0000 |
|  4 |   33000   |    2    | June, 21 2014 17:31:04+0000 |
|  5 |   20000   |    3    | June, 22 2014 17:31:04+0000 |
|  6 |   21000   |    3    | June, 23 2014 17:31:04+0000 |
+----+-----------+---------+-----------------------------+

I want to get last prices per item and one before last price's buy field based on a price date

Desired output:

+----+---------+-----------------+---------+
| id |   buy   | last_before_buy | item_id |
+----+---------+-----------------+---------+
| 10 |  45000  |     43000       |    3    |
| 7  |  33000  |     31000       |    2    |
| 4  |  23000  |     23000       |    1    |
+----+---------+-----------------+---------+

You can do this with the substring_index() / group_concat() trick:

select max(id) as id,
       substring_index(group_concat(buy order by created_at desc), ',', 1) as buy,
       substring_index(substring_index(group_concat(buy  order by created_at desc), ',', 2), ',', -1) as lastbuy,
       item_id
from prices p
group by item_id;

Here's another way to do it:

select a.id, a.buy, b.buy last_before_buy, a.item_id
from (select * from prices WHERE (created_at <= NOW() - INTERVAL 5 DAY) order by id desc) a
join (select * from prices order by id desc) b on a.item_id = b.item_id and a.id > b.id
group by a.item_id;

fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM