2013-11-03 85 views
1
Name  Price qty 
Deen  $11 150 
Ann  $12 100 
Anthony $13 250 
Anthony $13 250 
Anthony $14 150 

SELECT name, SUM(qty), MIN(price) FROM table GROUP BY name 

我需要通過集團的名稱,數量的總和,只有最低的價格作爲一個例子Mysql的ORDER BY和MIN

Name  Price qty 
    Deen  $11 150 
    Ann  $12 100 
    Anthony $13 500 

任何一個能幫助我的SQL?

+0

給定查詢有什麼問題? – Mureinik

+1

它不工作像例子itz給650數量 –

回答

2

所以這將是:

SELECT 
    t.Name, 
    MinPrices.MinPrice, 
    SUM(t.qty) AS SumQty 
FROM 
    (SELECT MIN(Price) AS MinPrice, Name FROM t GROUP BY Name) AS MinPrices 
    LEFT JOIN 
    t ON MinPrices.Name=t.Name 
    AND 
    MinPrices.MinPrice=t.Price 
GROUP BY 
    t.Name 

- 見這fiddle

1
SELECT 
    name, 
    MIN(price), 
    SUM(qty) 
FROM 
    table 
GROUP BY 
    name 
ORDER BY 
    2 

看看你再次查詢。我製作了一個和你一樣的表格,並提出了這個問題,它幾乎返回了你想要的結果,除了Anthony總和= 650。

+0

這是不正確的。它沒有給出預期的結果。 – peterm

1
SELECT 
    t1.name, 
    SUM(t1.qty), 
    t1.price 
FROM table t1 
WHERE 
    t1.price = (SELECT MIN(t2.price) FROM table t2 WHERE t1.name = t2.name) 
GROUP BY t1.name 
ORDER BY t1.price