Join

每個車型的 MAX 和 MIN

  • March 21, 2016

我有一個查詢問題。我有一個帶有汽車及其規格的數據庫,每個型號都有與該型號相關的不同汽車及其價格。我想創建一個查詢,為我提供每個模型的最低和最高價格。

像這樣的東西:

+--------+----------+
| model  | price    |
+--------+----------+
| golf   | 4000     | 
| golf   | 6000     |
| golf   | 10000    | 
| panda  | 3000     | 
| panda  | 5000     |
| panda  | 7000     |
+--------+----------+

查詢給了我這個:

+--------+----------+
| model  | price    |
+--------+----------+
| golf   | 4000     | 
| golf   | 10000    | 
| panda  | 3000     | 
| panda  | 7000     |
+--------+----------+

你能幫助我嗎?

您可以簡單地使用UNION ALL

SELECT model, MIN(price) price
FROM YourTable
GROUP BY model
UNION ALL
SELECT model, MAX(price) price
FROM YourTable
GROUP BY model;

引用自:https://dba.stackexchange.com/questions/132887