开发者

select least row per group in SQL

I am trying to select the min pric开发者_如何学运维e of each condition category. I did some search and wrote the code below. However, it shows null for the selected fields. Any solution?

SELECT Sales.Sale_ID, Sales.Sale_Price, Sales.Condition
FROM Items
LEFT JOIN Sales ON ( Items.Item_ID = Sales.Item_ID
AND Sales.Expires_DateTime > NOW( )
AND Sales.Sale_Price = (
SELECT MIN( s2.Sale_Price )
FROM Sales s2
WHERE Sales.`Condition` = s2.`Condition` ) )
WHERE Items.ISBN =9780077225957 


A little more complicated solution, but one that includes your Sale_ID is below.

SELECT TOP 1 Sale_Price, Sale_ID, Condition
FROM Sales
WHERE Sale_Price IN (SELECT MIN(Sale_Price) 
                     FROM Sales 
                     WHERE 
                     Expires_DateTime > NOW() 
                     AND 
                       Item_ID IN     
                         (SELECT Item_ID FROM Items WHERE ISBN = 9780077225957) 
                     GROUP BY Condition )

The 'TOP 1' is there in case more than 1 sale had the same minimum price and you only wanted one returned.

(internal query taken directly from @Michael Ames answer)


If you don't need Sales.Sale_ID, this solution is simpler:

SELECT MIN(Sale_Price), Condition
FROM Sales
WHERE Expires_DateTime > NOW()
AND Item_ID IN
    (SELECT Item_ID FROM Items WHERE ISBN = 9780077225957)
GROUP BY Condition

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜