从1列中选择不同的值

Par*_*arm 24 sql sql-server sql-server-2005 distinct

我想用这个查询从一列(BoekingPlaatsId列)中选择不同的值:

SELECT MAX(BoekingPlaatsId), BewonerId, Naam, VoorNaam
FROM table
GROUP BY BewonerId, Naam, VoorNaam
Run Code Online (Sandbox Code Playgroud)

我如何在SQL Server中执行此操作?

doz*_*oza 20

DISTINCT 如果你只想要用户名,应该工作:

SELECT DISTINCT BewonerId, Naam, Voornaam
FROM TBL
Run Code Online (Sandbox Code Playgroud)

但如果您需要最小ID值,请按名称分组......

SELECT MIN(BoekingPlaatsId), MIN(BewonerId), Naam, Voornaam
FROM TBL
GROUP BY Naam, Voornaam
Run Code Online (Sandbox Code Playgroud)

  • 对于一张小桌子来说,按一切进行分组是很好的,但它对于一张大桌子来说很糟糕. (3认同)

San*_*ken 7

我认为你应该可以使用

SELECT DISTINCT BewonerId, Naam, VoorNaam
Run Code Online (Sandbox Code Playgroud)

您无法添加BoekingPlaatsId,因为:

  • DISTINCT寻找独特的
  • 你需要指定BoekingPlaatsId你想要的值
    (如果是Jan Janssens,你想要BoekingPlaatsId 1还是2?)

还有用的是:

SELECT MAX(BoekingPlaatsId), BewonerId, Naam, VoorNaam
FROM ...
GROUP BY BewonerId, Naam, VoorNaam
Run Code Online (Sandbox Code Playgroud)


Pau*_*sey 6

我不会做很多这样的事情,所以我不是100%确定语法,因此您可能需要稍作调整,将google排名并进行分区。尝试这个...

SELECT 
    *,
    RANK() OVER(PARTITION BY Naam  order by Naam ) as Rank
FROM
    TABLE
WHERE 
    Rank = 1
Run Code Online (Sandbox Code Playgroud)

对于4列表来说,这是过大的杀伤力,但是如果您有一个包含许多列的相当不规范的表,则此方法对于选择1列上的非重复值非常有用。