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

前端 未结 4 2033
無奈伤痛
無奈伤痛 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-27 23:51

    If I understand what you're wanting...

    This will get you the First Names:

    SELECT *
    FROM [NameTable]
    WHERE FrequencyPercent > 1.0
        AND NameType = 1
    ORDER BY FrequencyPercent
    
    0 讨论(0)
  • 2021-01-27 23:53

    If you want top 2 for both first and last name, you can do UNION ALL.

    select name 
    FROM table
    where Nametype = 1
    order by FrequencyPercent desc
    limit 2
    UNION ALL
    select name 
    from table
    where nametype = 2
    order by FrequencyPercent desc
    limit2
    
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-28 00:16

    Top 5 most common first names:

    select Name
      from Names
      where NameType = 1
      order by FrequencyPercent desc
      limit 5;
    
    0 讨论(0)
提交回复
热议问题