2013-04-13 170 views
0

我的問題是有關一個選擇,我想訂購由ASC和DESC字段,看一下例子:訂購最高和最低

我有表的產品,我要訂購的場所謂的價格,所以,我知道我能做到這一點:

SELECT Price FROM Products ORDER BY Price ASC. 

但我想看到的最高價和最低價,爲最高的,我知道我能做到:

SELECT Price FROM Products ORDER BY Price ASC limit 1; 

那麼,如何我可以選擇最高值和最低值,機器人h在1選擇?

我也想要選擇具有最高價值的產品的名稱和具有最低價值的產品。

問候。

+0

你只是想價格或整排設有此價格是多少?你將如何打破關係(多行共享最低/最高)?挑一個任意一個?返回所有同齡人? –

回答

2

這將顯示所有產品的最高價或最低價:

SELECT Products.* 
FROM Products 
WHERE Price = (SELECT MAX(Price) FROM Products) 
     OR Price = (SELECT MIN(Price) FROM Products) 

或者,也許你想是這樣的:

SELECT 
    Products.*, 
    m.mx As Highest, 
    m.mn As Lowest, 
    CASE WHEN Products.Price = m.mx THEN 'Max' ELSE 'Min' END As Is_Max_or_Min 
FROM 
    Products INNER JOIN (
    SELECT MAX(Price) mx, MIN(Price) mn 
    FROM Products 
) m ON Products.Price IN (m.mx, m.mn) 

如果您希望他們在同一排,如果只有一個產品價格最高,而最低價格只有一個產品,則可以使用如下所示:

SELECT 
    m.Lowest, p1.Name Name_Lowest, 
    m.Highest, p2.Name Name_Highest 
FROM 
    (SELECT MIN(Price) Lowest, MAX(Price) Highest FROM Products) m 
    INNER JOIN Products p1 ON m.Lowest = p1.Price 
    INNER JOIN Products p2 ON m.Highest = p2.Price 
LIMIT 1 

或者,如果你只是需要一些easyer,你可以這樣做:

(SELECT 'Max' Is_Max_Or_Min, Products.* 
FROM Products ORDER BY Price DESC LIMIT 1) 
UNION ALL 
(SELECT 'Min', Products.* 
FROM Products ORDER BY Price LIMIT 1) 
+0

好的,...在一個選擇?如果可能的話:) – Tennosuke

+0

@Tennosuke我已經更新了我的最後一個查詢,我想這是你正在尋找的...請讓我知道如果沒關係:) – fthiella

+0

是如此艱難?有沒有更簡單的方法? – Tennosuke

0

SELECT Price FROM Products ORDER BY Price DESC limit 1; ??

+0

在1選擇;) – Tennosuke

0

,如果你想看到兩個最高和最低的價格,使用此查詢:

select highest, lowest from 
(
SELECT Price as highest FROM Products ORDER BY Price DESC limit 1; 
SELECT Price as lowest FROM Products ORDER BY Price ASC limit 1; 
) t 
4

怎麼樣使用簡單MINMAX聚合函數的

SELECT MAX(Price) as MaxPrice, MIN(Price) as MinPrice FROM Products 
+0

它的作品,謝謝! – Tennosuke

0

最簡單的方法是:

SELECT MIN(Price) LowestPrice, MAX(Price) HighestPrice FROM Products 

但在某些情況下,您可能希望使用UNION聲明:

(SELECT 'Lowest' type, Price FROM Products ORDER BY Price ASC LIMIT 1) 
UNION 
(SELECT 'Highest' type, Price FROM Products ORDER BY Price DESC LIMIT 1) 
+0

現在有點難度,除了價格,如果我想產品的名稱最高和最低?你怎麼看? – Tennosuke