Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

MySQL price & stock comparison

I have a follow-up question to my original post (MySQL Compare prices)

Lets say I have table1 containing the following columns;

EXAMPLE 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

What I have now achieved (by help of @Ali) is for table1 to show the following (which basically shows the supplier with the cheapest price for the product):

EXAMPLE 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

HOWEVER: IF the stock of the supplier with the cheapest price is 0 but another supplier has more than 0 in stock, eventhough the price isn't the cheapest, how could I achieve that? Following the example West would take the place of East as below:

EXAMPLE C)

 |item   |partnumber |supplier  |stock  |cost 
  CD      11A          West       11     10.11
  USB     BBB          West       1      101.10

To be more clear; always show the supplier with the cheapest item in stock, unless the cheapest supplier doesn't have the item in stock but another one do, in which case show that instead. So, how can I achieve EXAMPLE C)?

Thank you very much!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have you tried just adding a where condition inside the subquery?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...