我有一个名为“价格”的表。其中包含ID、fkProductID(产品表的外键)、PriceDate、Price、fkStore(给出价格的供应商ID)
现在我需要找到每个月每种产品的最优惠价格以及供应商名称。 一些供应商还给出重复的价格。例如,产品 id 8 的值是 1200 的两倍(ID# 8 和 3)。如果可能的话,我只需要显示第一个供应商或具有计数值的列..
ID fkProductID PriceDate Price fkStore
-----------------------------------------------------
1 8 26-10-2014 1250 13
2 8 10-09-2014 1200 13
3 8 25-10-2014 1200 1
4 8 13-10-2014 1500 1
5 8 03-09-2014 1000 1
6 8 15-09-2014 1300 15
7 8 09-09-2014 950 21
8 8 10-10-2014 1200 23
9 8 09-09-2014 950 27
10 15 10-10-2014 3500 5
11 15 11-10-2014 3400 6
12 15 09-09-2014 3100 6
13 15 10-09-2014 3200 14
14 15 16-09-2014 3100 17
-----------------------------------------------------
我的预期结果。
-----------------------------------------------------
ID fkProductID Month Price Supplier
-----------------------------------------------------
7 8 September 950 21
2 8 October 1200 1
13 15 September 3100 13
11 15 October 3400 6
====================================================== ================
你可以用
substring_index()
/group_concat()
技巧做你想做的事:
select substring_index(group_concat(idPrices order by Price, idPrices), ',', 1) as id,
fkProductId, monthname(PriceDate) as mon,
min(Price) as price,
substring_index(group_concat(fkStore order by Price, idPrices), ',', 1) as spec_id
from prices p
group by fkProductId, monthname(PriceDate);