簡體   English   中英

按日期獲取每個類別的最后一條記錄過濾器

[英]get last record per category filter by date

我有這張表SQL Fiddle

項目表:

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

價格表:

+----+-----------+---------+-----------------------------+
| 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 |
+----+-----------+---------+-----------------------------+

我想根據價格日期獲取每件商品的最后價格和最后價格的購買字段之前的價格

所需的輸出:

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

您可以使用substring_index() / group_concat()技巧來做到這一點:

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;

這是另一種方法:

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;

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM