Sql-Server

SQL:根據另一列的聚合選擇分組中的列

  • November 7, 2019

假設我有以下格式的表格

UID  |  A  |  B
----------------
1       2     1
2       5     1
3       4     1
4       3     2
5       8     2
6       7     2
7       4     3
8       1     3
9       6     3

我想選擇與按 B 分組的 MAX(A) 對應的 UID

以下語句不起作用,因為 MAX(UID) 獨立於 MAX(A)

SELECT MAX(UID), MAX(A), B
FROM Table
GROUP BY B

我想要返回的數據如下

UID  |  A  |  B
----------------
2       5     1
5       8     2
9       6     3

你需要這樣的東西:

SELECT t1.UID, t1.A, t1.B
FROM Table t1
INNER JOIN (
SELECT MAX(A) as A, B
FROM Table
GROUP BY B) T2 ON T1.A = T2.A AND T1.B = T2.B

有幾種方法可以做到這一點,但基本前提是相同的。找到每個 B 和 MAX(A) 組合併將此結果集連接回源表中的這些列以返回 UID。這個db<>fiddle突出了兩種可能的簡單解決方案。

每個的程式碼:

/* Option #1 */
WITH MaxBs AS (
 SELECT B, MAX(A) AS A
 FROM TestData
 GROUP BY B
)

SELECT t.UID, t.A, t.B
FROM TestData t
INNER JOIN MaxBs b ON b.B = t.B and b.A = t.A
ORDER BY UID

/* Option #2 */

SELECT t.UID, t.A, t.B
FROM TestData t
INNER JOIN 
(
 SELECT MAX(A) as A, B
 FROM TestData
 GROUP BY B
) b ON t.A = b.A AND t.B = b.B

這兩個都返回您想要的結果集:

UID  |  A  |  B
---------------
2       5     1
5       8     2
9       6     3

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