我有兩張桌子 - 產品和價格如何獲得與上個月相比最大的差異?
每個月的表格每個產品的價格都會包含新的價格。我怎樣才能得到5種價格與上個月價格差距最大的產品?
表產品
id | name
1 | apples
2 | pears
3 | bananas
表價格
id | price | product_id | created_at
1 | 10 | 1 | 2017-02-07 07:00:00
2 | 10 | 2 | 2017-02-07 07:00:00
3 | 15 | 3 | 2017-02-07 07:00:00
5 | 15 | 1 | 2017-03-07 07:00:00
6 | 20 | 2 | 2017-03-07 07:00:00
7 | 25 | 3 | 2017-03-07 07:00:00
其結果將是找出
1. Bananas has prices by 15 higher (lastMonth: 15, now: 25)
2. Pears 2 has prices by 10 higher (lastMonth: 10, now: 20)
3. Apples has prices by 5 higher (lastMonth: 10, now: 15)
我在想這樣的事情(UFF我知道這是可怕的)
SELECT products.id, products.name, prices.beforePrice, prices.afterPrice, prices.difference
FROM products
INNER JOIN prices ON products.id = prices.product_id
WHERE
(
SELECT *biggest-difference*
FROM prices
WHERE *difference_between_last_2_months*
GROUP BY product_id
LIMIT 5
)
謝謝,這個作品,雖然我得到了重複的產品。在開始放置「SELECT DISTINCT」似乎解決了這個問題。再次感謝 :) –