SQL – 只在一列上select不同的名称

我对这个问题的答案已经广泛搜寻。 我正在使用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 | 

我想执行一个只select唯一的“NUMBER”列的查询(不pipe是第一行还是最后一行都不打扰我)。 所以这会给我:

 +--------+---------+-------------+-------------+ | ID | NUMBER | COUNTRY | LANG | +--------+---------+-------------+-------------+ | 1 | 3968 | UK | English | | 4 | 1234 | Greece | Greek | 

这是如何实现的?

既然你不在乎,我select了每个号码的最大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 

这种types的问题的一个非常典型的方法是使用row_number()

 select t.* from (select t.*, row_number() over (partition by number order by id) as seqnum from t ) t where seqnum = 1; 

这比使用最小的id比较更普遍。 例如,你可以通过使用order by newid()来得到一个随机的行。 您可以使用where seqnum <= 2来select2行。

您将使用以下查询:

 SELECT * FROM [table] GROUP BY NUMBER; 

其中[table][table]的名称。

这为NUMBER列提供了一个唯一的列表,但其他列根据供应商的实现可能没有意义; 也就是说他们可能不一起对应一个特定的行或行。