这个问题已经在这里有了答案 :
如何通过SQL中的另一列选择具有MAX(列值),DISTINCT的行? (19个回答)
7年前关闭。
我已经四处搜寻有关此问题的答案。我正在使用Microsoft SQL Server,假设我有一个看起来像这样的表:
+--------+---------+-------------+-------------+ | ID | NUMBER | COUNTRY | LANG | +--------+---------+-------------+-------------+ | 1 | 3968 | UK | English | | 2 | 3968 | Spain | Spanish | | 3 | 3968 | USA | English | | 4 | 1234 | Greece | Greek | | 5 | 1234 | Italy | Italian |
我想执行一个查询,该查询仅选择唯一的“ NUMBER”列(无论是第一行还是最后一行都不会打扰我)。所以这会给我:
+--------+---------+-------------+-------------+ | ID | NUMBER | COUNTRY | LANG | +--------+---------+-------------+-------------+ | 1 | 3968 | UK | English | | 4 | 1234 | Greece | Greek |
这是如何实现的?
由于您不在乎,因此我为每个数字选择了最大ID。
select tbl.* from tbl inner join ( select max(id) as maxID, number from tbl group by number) maxID on maxID.maxID = tbl.id
查询说明
select tbl.* -- give me all the data from the base table (tbl) from tbl inner join ( -- only return rows in tbl which match this subquery select max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below from tbl group by NUMBER -- how to group rows for the MAX aggregation ) maxID on maxID.maxID = tbl.id -- join condition ie only return rows in tbl -- whose ID is also a MAX ID for a given NUMBER