SQL Server equivalent of PostgreSQL distinct on ()

前端 未结 2 1892
深忆病人
深忆病人 2021-02-12 10:45

I would like to have a Sql Server equivalent of the PostgreSQL distinct on ()

a  b
----
1  1
1  2
2  2
2  1
3  3

select distinct on (a) * 
from my_         


        
相关标签:
2条回答
  • 2021-02-12 11:01

    You can try ROW_NUMBER, but it can affect your performance.

    ;WITH CTE AS
    (
        SELECT *, ROW_NUMBER() OVER(PARTITION BY a ORDER BY b) Corr
        FROM my_table
    )
    SELECT *
    FROM CTE
    WHERE Corr = 1
    
    0 讨论(0)
  • 2021-02-12 11:02

    In addition to the accepted answer, you can avoid using two sentences and use a sub select like this

    SELECT part.*
    FROM (  SELECT *, ROW_NUMBER() OVER(PARTITION BY a ORDER BY b) Corr
        FROM my_table) part
    WHERE part.Corr = 1
    
    0 讨论(0)
提交回复
热议问题