SQL/mysql - Select distinct/UNIQUE but return all columns?

前端 未结 18 1095
忘掉有多难
忘掉有多难 2020-11-22 12:08
SELECT DISTINCT field1, field2, field3, ......   FROM table

I am trying to accomplish the following sql statement but I want it to return all colum

18条回答
  •  失恋的感觉
    2020-11-22 12:16

    For SQL Server you can use the dense_rank and additional windowing functions to get all rows AND columns with duplicated values on specified columns. Here is an example...

    with t as (
        select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r1' union all
        select col1 = 'c', col2 = 'b', col3 = 'a', other = 'r2' union all
        select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r3' union all
        select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r4' union all
        select col1 = 'c', col2 = 'b', col3 = 'a', other = 'r5' union all
        select col1 = 'a', col2 = 'a', col3 = 'a', other = 'r6'
    ), tdr as (
        select 
            *, 
            total_dr_rows = count(*) over(partition by dr)
        from (
            select 
                *, 
                dr = dense_rank() over(order by col1, col2, col3),
                dr_rn = row_number() over(partition by col1, col2, col3 order by other)
            from 
                t
        ) x
    )
    
    select * from tdr where total_dr_rows > 1
    

    This is taking a row count for each distinct combination of col1, col2, and col3.

提交回复
热议问题