How to get get Unique Records based on multiple columns from a table

前端 未结 3 1633
小鲜肉
小鲜肉 2021-01-07 09:57

Consider the following table:

primaryKey   id    activity   template  creator   created
1            1      3           5         x       2011-10-13
2                


        
相关标签:
3条回答
  • 2021-01-07 10:11

    I think this should work -

    SELECT * 
    FROM TABLE
    WHERE 
     primaryKey in 
     (
       SELECT min(primarkyKey) from TABLE 
          group by id, activity, template
     )
    

    Here, first distinct is obtain on required columns in the inner query by doing group by. Then the min of primary key of each distinct record is used to get all the columns from the outer query.

    0 讨论(0)
  • 2021-01-07 10:14

    This is for MS SQL Server.

    Updated, as i made a little mistake!

    SELECT DISTINCT 
            ROW_NUMBER() OVER (ORDER BY 
                                    id    
                                ,   activity   
                                ,   template  
                                ,   creator  
                                ,   created ) PrimaryKey
    
        ,   id    
        ,   activity   
        ,   template  
        ,   creator  
        ,   created 
        FROM 
        [TABLE_NAME]
        GROUP BY 
    
            id    
        ,   activity   
        ,   template  
        ,   creator  
        ,   created 
    
    0 讨论(0)
  • 2021-01-07 10:27
    SELECT primarykey, id, activity, template, creator, created FROM (
        SELECT *, row_number() OVER (partition BY id, activity, template ORDER BY created) as rn FROM table
    ) a 
    WHERE rn = 1
    
    0 讨论(0)
提交回复
热议问题