SQL: How can I return the highest ranking record of similar records, based on one column value?

前端 未结 4 2035
無奈伤痛
無奈伤痛 2021-01-27 23:22

This seems like it should be easier than I\'m finding it. I have a table that contains both first and last names (specified by a type ID) and a frequency of how common the name

4条回答
  •  孤街浪徒
    2021-01-28 00:01

    If I understand correctly you're looking for first names when the frequency is higher than the frequency as same name as last name

    This works for first names. You just need to reverse it for last names

    CREATE Table YourTable
    (
    NameType int,
    name varchar(20),
    FrequencyPercent decimal(12,4)
    )
    
    INSERT INTO  YourTable
    VALUES (1 ,'John', 3.267),
    (1 , 'Thomas',      1.987),
    (1 , 'Wilson',      0.945),
    (2 , 'Smith',       4.528),
    (2 ,  'Wilson',      2.221),
    (2 ,   'Thomas',      0.437)
    
    SELECT firstNames.name
    FROM
          YourTable firstNames 
    LEFT JOIN YourTable  lastNames 
     ON firstnames.Name = lastNames.Name
        AND lastNames.NameType  =2
         and firstnames.FrequencyPercent < lastNames.FrequencyPercent
    WHERE firstNames.NameType  =1
          AND
          lastNames.name is null
    

    results in

    name
    --------------------
    John
    Thomas
    (2 row(s) affected)
    

提交回复
热议问题