2016-10-27 56 views
1

因此,我有1個MySQL表格,其中包含銷售額以及銷售價格和時間。我有第二個表格,每5分鐘記錄一次市場上每件商品的平均價格。這些東西可以改變價格分鐘。加入2個表格來尋找最近的時間戳

我需要從銷售時間兩個銷售時間之前和之後銷售的每個項目獲得表2的市場價格。

我一直在試圖將它分成先取得價格和出售後的價格作爲兩個單獨的查詢。我目前得到的是以下。但它的問題在於,它只在行設置完畢後纔會下達market.time。我需要它通過市場排序。在GROUP BY語句選擇每個sales.id的最上面一行之前(希望這是有道理的)。基本上它會返回已售出物品的最早價格,然後整個表格按這些時間排序。

SELECT sales.id, sales.price, sales.time, sales.item_id, market.time, market.price, 
FROM sales_table sales 
INNER JOIN market_table market ON market.item_id = sales.item_id 
WHERE market.time < sales.time 
GROUP BY sales.id 
ORDER BY market.time DESC; 

銷售表

| id | price|   time     | item_id | 
-------------------------------------------------------- 
| 1 |  0.5 | 2006-10-05 11:55:44  | 5  | 
| 2 |  1.1 | 2007-10-07 12:34:17  | 5  | 
| 3 |  0.4 | 2008-10-09 08:19:36  | 9  | 
| 4 |  5.8 | 2010-10-13 04:28:14  | 1  | 

市場表

| id | price|   time     | item_id | 
-------------------------------------------------------- 
| 1 |  0.5 | 2006-10-05 11:50:00  | 1  | 
| 2 |  1.1 | 2006-10-05 11:55:00  | 1  | 
| 3 |  0.4 | 2008-10-09 02:20:00  | 2  | 
| 4 |  5.8 | 2010-10-09 04:25:00  | 2  | 

期望的結果

| s_id | s_price|  sales_time  | item_id| market_time  |m_price 
---------------------------------------------------------------------------- 
| 1 | 0.5 | 2006-10-05 11:55:44 | 5  | 2006-10-05 11:55:00| 0.5 
| 2 | 1.1 | 2007-10-07 12:34:17 | 5  | 2007-10-07 12:30:00| 1.2 
| 3 | 0.4 | 2008-10-09 08:19:36 | 9  | 2008-10-09 08:15:00| 0.45 
| 4 | 5.8 | 2010-10-13 04:28:14 | 1  | 2010-10-13 04:25:00| 6.0 

什麼,我現在從我上面的查詢得到

| s_id | s_price|  sales_time  | item_id| market_time  |m_price 
---------------------------------------------------------------------------- 
| 1 | 0.5 | 2006-10-05 11:55:44 | 5  | 2001-01-01 00:00:00| 1.0 
| 2 | 1.1 | 2007-10-07 12:34:17 | 5  | 2002-06-01 09:15:00| 0.8 
| 3 | 0.4 | 2008-10-09 08:19:36 | 9  | 2002-08-14 15:30:00| 0.2 
| 4 | 5.8 | 2010-10-13 04:28:14 | 1  | 2003-10-01 12:00:00| 5.2 
+0

見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very -simple-sql-query – Strawberry

+0

@Strawberry Ouch ...我很高興這不是我的問題;-) –

+1

@TimBiegeleisen我仍然在枉然的希望之下工作,如果我經常說得夠多,消息最終可能會通過給某人。 – Strawberry

回答

0

請按行數使用。

select id, time, price, time, price from (
    SELECT sales.id, sales.time, sales.price, market.time, market.price, row_number() over (partition by sales.id order by ABS(DATEDIFF(SECOND, market.time, sales.time))) as r 
    FROM sales_table sales 
    INNER JOIN market_table market ON market.item_id = sales.item_id 
) as t 
where t.r = 1 
ORDER BY market.time DESC; 
+0

這個問題似乎與MySQL – Strawberry

+0

有關,想知道爲什麼我在row_number部分出現錯誤。 – mehigasf