2014-06-28 39 views
0

我有這個表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 | 
+----+---------+-----------------+---------+ 
+0

你應該拉你的起始數據在這裏,只是爲了防止鏈接腐爛。你有什麼嘗試?這聽起來像是以[標籤:最大n組]問題開始,沒有任何標準答案可以工作嗎? –

+0

@ Clockwork-Muse我添加了數據,我的問題由加工商解決,tnx – Sam

回答

0

這裏是另一種方式來做到這一點:

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

+0

tnx與此我得到最後的結果我怎麼能得到例如最後一個項目與他們的價格1周前? – Sam

+0

是否在派生表中使用'order by id desc'確保最近的'a.buy'被選中? – FuzzyTree

+0

@Xengil,在任意時間之前,您將'a.id> b.id'更改爲'b.trade_time Fabricator

0

您可以用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; 
+0

添加此以符合他的願望'訂單id desc' –

相關問題