2014-10-01 43 views
0

這裏是我的SQL表:Sql gruoup by子句沒有獲取想要的結果?

Item_id  city_product_id       auto_inc price  

1. XYZ   CHDELCLAPTOPDELLINSPIRON     1   1500 
2. ABCD  CHDELCLAPTOPDELLVOSTR816     2   1200 
3. ABCD  CHDELCLAPTOPDELLVOSTR816     3   1000 

這裏是我的SQL查詢:

SELECT city_product_id, item_id, auto_inc, MIN(price) AS minPrice 
FROM sellers_product GROUP BY city_product_id 

該查詢返回的輸出:

city_product_id   item_id  auto_inc  price  

    CHDELCLAPTOPDELLINSPIRON XYZ    1  1500 

    CHDELCLAPTOPDELLVOSTR816 ABCD    2  1000 

唯一的問題就是爲什麼它是返回auto_inc爲2時它應該返回3因爲1000小於1200.

+0

嘗試包括BY子句集團'auto_inc'爲好。 – 2014-10-01 10:00:21

+0

@AnkitBajpai不,它沒有工作 – AK2 2014-10-01 10:01:23

+0

這是一種方法,根據需要進行更改http://www.sqlfiddle.com/#!2/385f0/3 – 2014-10-01 10:01:52

回答

3

在組中存在非聚集的領域由會給你可以使用自不確定的結果加入,以確定與最小的代價正確的行

SELECT p.* 
FROM sellers_product p 
join (select city_product_id,MIN(price) AS minPrice 
     from sellers_product 
     GROUP BY city_product_id) p1 
on(p.city_product_id = p1.city_product_id and p.price = p1.minPrice) 

Demo

3

MySQL的小組,由函數使用第一代遇到行以填充結果行中任何未分組字段的值。

SELECT city_product_id, item_id, auto_inc, price 
from (SELECT * 
     FROM sellers_product  
     ORDER BY price ASC) AS h 
GROUP BY city_product_id; 

http://sqlfiddle.com/#!2/2d5b2/1

+0

MySQL的最糟糕的功能之一,喲! – DavidG 2014-10-01 10:07:24

+0

震驚知道這........... – 2014-10-01 10:23:47