Select distinct values from 1 column

后端 未结 9 2073
忘了有多久
忘了有多久 2020-12-10 00:47

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

SELECT MAX(BoekingPlaatsId), BewonerId, Naam, VoorNaam
F         


        
相关标签:
9条回答
  • 2020-12-10 01:24

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

    select distinct column1 from table1 where column2 = (select distinct column2 from table1)
    
    0 讨论(0)
  • 2020-12-10 01:27

    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.

    0 讨论(0)
  • 2020-12-10 01:27

    This is how you can select from a table with only unique values for your column:

    CREATE VIEW [yourSchema].[v_ViewOfYourTable] AS
    WITH DistinctBoekingPlaats AS
    (
        SELECT [BewonerId], 
               [Naam],
               [VoorNaam],
               [BoekingPlaatsId],
               ROW_NUMBER() OVER(PARTITION BY [BoekingPlaatsId] ORDER BY DESC) AS 'RowNum'
        FROM [yourSchema].[v_ViewOfYourTable]
    )
    SELECT * 
    FROM DistinctProfileNames
    WHERE RowNum = 1
    --if you would like to apply group by you can do it in this bottom select clause but you don't need it to gather distinct values 
    

    You don't need group by to accomplish this.

    0 讨论(0)
  • 2020-12-10 01:30
    select Naam, Voornaam, min(BewonerId), min(BoekingPlaatsId) from tableName
    group by Naam, Voornaam
    
    0 讨论(0)
  • 2020-12-10 01:34

    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
    
    0 讨论(0)
  • 2020-12-10 01:38

    just group By those 2 columns

      Select Min(BoekingPlaatsId), Min(bewonerId), naam, voornaam
      from table
      group By naam, voornaam
    
    0 讨论(0)
提交回复
热议问题