![](/img/trans.png)
[英]Select rows with Max(Column Value) for each unique combination of two other columns
[英]Get whole dataset for each unique combination of two columns and their max and min values
我拼命地搜索一個查詢,該查詢將所有數據集提供給以下查詢:
SELECT col1, col2, MAX(col3), MIN(col4) FROM table1 GROUP BY col1, col2
這將返回一個如下表
col 1 | col2 | max(col3) | min(col4)
------ | ------ | --------- | ------
10 | 0.5 | 20 | -5
10 | 0.9 | 30 | -2
我需要的是每個最大值和最小值以及每個實體的數據集(整行)。 我可以像這樣的查詢以編程方式執行此操作
SELECT * FROM table1 WHERE col1 = 10 AND (col2 = 0.5 OR col2 = 0.9) AND ((col3 = 20 OR col4 = -5) OR (col3 = 30 OR col4 = -2 ))
它返回了我4個數據集,
但是每添加一個MAX或MIN或GROUP BY,查詢都會變得更加難看(這是用戶對程序的處理方式)。
讓我嘗試用一句話來解釋它:我正在尋找一種將數據集顯示為col1和col2值的每個唯一組合的每個最大值和最小值(不是col1,col2)的一種方式。
有沒有辦法在一個查詢中做到這一點?
如果您需要更多詳細信息,請不要害怕發表評論。
數據集
id | col 1 | col2 | col3 | col4
---- | ------ | ------ | ------ | ------
0 | 10 | 0.5 | 20 | 0
1 | 10 | 0.5 | 15 | -1
2 | 10 | 0.5 | 17 | 12
3 | 10 | 0.5 | 11 | 3
4 | 10 | 0.5 | 5 | -5
5 | 10 | 0.9 | 10 | 1
6 | 10 | 0.9 | 22 | -1
7 | 10 | 0.9 | 15 | -2
8 | 10 | 0.9 | 30 | 3
期望的輸出
id | col 1 | col2 | col3 | col4
---- | ------ | ------ | ------ | ------
0 | 10 | 0.5 | 20 | 0
4 | 10 | 0.5 | 5 | -5
7 | 10 | 0.9 | 15 | -2
8 | 10 | 0.9 | 30 | 3
如果您知道兩個列的值:這將是這兩個列值的col3最大值和col 4最小值時的數據集。 請記住,您對查詢的約束是兩個列的值。 復合查詢應類似於:
select * from table1 as A where col1 = '$value1' and col2 = '$value2' and col3=(select MAX(col3) FROM table1 as B where A.col1 = B.col1 and A.col2 = B.col2) and col4=(select MIN(col4) FROM table1 as C where A.col1 = C.col1 and A.col2 = C.col2)";
應該這樣做:
SELECT A.* FROM
table1 A
INNER JOIN
(SELECT
col1,
col2,
MAX(col3) AS MAX_col3,
MIN(col4) AS MIN_col4
FROM table1
GROUP BY
col1,
col2) B
ON A.col1 = B.col1
AND A.col2 = B.col2
AND A.col3 = B.MAX_col3
AND A.col4 = B.MIN_col4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.