views:

485

answers:

7

I want to select distinct values from only one column (the BoekingPlaatsId column) with this query:

SELECT MAX(BoekingPlaatsId), BewonerId, Naam, VoorNaam
FROM table
GROUP BY BewonerId, Naam, VoorNaam

How do I do that in SQL Server?

+2  A: 

DISTINCT should work if you just want the user names:

SELECT DISTINCT BewonerId, Naam, Voornaam
FROM TBL

but if you need the minimum ID values, group by the names...

SELECT MIN(BoekingPlaatsId), MIN(BewonerId), Naam, Voornaam
FROM TBL
GROUP BY Naam, Voornaam
doza
Grouping by everything is fine for a small table but it sucks for a large table.
Paul Creasey
A: 

just group By those 2 columns

  Select Min(BoekingPlaatsId), Min(bewonerId), naam, voornaam
  from table
  group By naam, voornaam
Charles Bretana
A: 
select Naam, Voornaam, min(BewonerId), min(BoekingPlaatsId) from tableName
group by Naam, Voornaam
BlackTigerX
A: 

I think what you're looking for is something like this:

select distinct column1 from table1 where column2 = (select distinct column2 from table1)
Michael
subquery is not scalar
Paul Creasey
A: 

I think you should be able to use

SELECT DISTINCT BewonerId, Naam, VoorNaam

You can't add BoekingPlaatsId, because:

  • DISTINCT looks for unique rows
  • You need to specify what BoekingPlaatsId value you want
    (In case of Jan Janssens, do you want BoekingPlaatsId 1 or 2?)

What also works is this:

SELECT MAX(BoekingPlaatsId), BewonerId, Naam, VoorNaam
FROM ...
GROUP BY BewonerId, Naam, VoorNaam
Sander Rijken
Jup dude! your second query worked like a charm! this is my first time on these forums but you guys convinced me well! I'll be surfing around here again! I think I'll be learning a lot from you guys! Problem solved ;)
Parm
A: 

I don't do alot of this so i'm not 100% certain of the syntax so you may need to tweak it slightly, google rank over and partition. Try this...

SELECT 
    *,
    RANK() OVER(PARTITION BY Naam  order by Naam ) as Rank
FROM
    TABLE
WHERE 
    Rank = 1

This is overkill for a 4 column table, but if you have a fairly denormalised table with alot of columns, this approach is invaluable for select distinct on 1 column.

Paul Creasey
A: 

Sounds like you want something like

select distinct(BewonerId), Naam, Voornaam from table_name
mmorrisson