我对原帖(MySQL Compare prices)
提出了跟进问题假设我有table1包含以下列;
示例A)
|item |partnumber |supplier |stock |cost
CD 11A West 11 10.11
CD 11A East 0 10.00
USB BBB North 1 125.01
USB BBB West 1 101.10
我现在所获得的(通过@Ali的帮助)是为了表1显示以下内容(基本上显示了产品最便宜的供应商):
例B)
|item |partnumber |supplier |stock |cost
CD 11A East 0 10.00
USB BBB West 1 101.10
This is the code for EXAMPLE B that is working:
SELECT a.name , a.partnumber , a.supplier , a.cost FROM table1 a JOIN (
SELECT name , partnumber , MIN(cost) cost
FROM table1
GROUP BY name , partnumber )
b ON a.name = b.name AND a.cost = b.cost AND a.partnumber = b.partnumber
但是:如果最便宜的供应商的库存是0但另一个供应商的库存超过0,尽管价格不是最便宜的,我怎么能实现呢?以示例为例,West将取代East,如下所示:
示例C)
|item |partnumber |supplier |stock |cost
CD 11A West 11 10.11
USB BBB West 1 101.10
更清楚;总是向供应商展示最便宜的库存商品,除非最便宜的供应商没有库存商品而另一商品商品,在这种情况下显示相反。那么,我怎样才能实现例C)?
非常感谢!
答案 0 :(得分:0)
您是否尝试在子查询中添加where条件?
SELECT a.name , a.partnumber , a.supplier , a.cost FROM table1 a JOIN ( SELECT name , partnumber , MIN(cost) cost FROM table1 where stock > 0 GROUP BY name , partnumber ) b ON a.name = b.name AND a.cost = b.cost AND a.partnumber = b.partnumber
答案 1 :(得分:0)
试试这个:
select a.item,a.partnumber,b.supplier,a.stock,min(a.cost) from
(select item,partnumber,supplier,stock,min(cost) cost from
(select * from table1) as a where stock !=0
group by item,partnumber) as a
LEFT JOIN
(select item,partnumber,supplier,stock,cost from
(select * from table1) as a where stock !=0) as b
on a.cost = b.cost
group by a.item,a.partnumber
结果:
CD 11A West 11 10.11
USB BBB West 1 101.1