加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQL Server相当于PostgreSQL distinct on()

发布时间:2020-12-12 08:22:52 所属栏目:MsSql教程 来源:网络整理
导读:我想要一个Sql Server相当于PostgreSQL distinct on() a b----1 11 22 22 13 3select distinct on (a) * from my_tablea b----1 12 23 3 我可以在SQL Server中做: select a,min(b) -- or max it does not matterfrom my_tablegroup by a 但是在有很多列的情
我想要一个Sql Server相当于PostgreSQL distinct on()
a  b
----
1  1
1  2
2  2
2  1
3  3

select distinct on (a) * 
from my_table

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

我可以在SQL Server中做:

select a,min(b) -- or max it does not matter
from my_table
group by a

但是在有很多列的情况下,查询是一个特殊的查询是非常繁琐的.有没有办法做到这一点?

解决方法

您可以尝试ROW_NUMBER,但可能会影响您的效果.
;WITH CTE AS
(
    SELECT *,ROW_NUMBER() OVER(PARTITION BY a ORDER BY b) Corr
    FROM my_table
)
SELECT *
FROM CTE
WHERE Corr = 1

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读