SQL Server 相当于 PostgreSQL 的 unique on ()

发布于 2024-11-04 00:47:09 字数 373 浏览 0 评论 0原文

我希望有一个相当于 PostgreSQL distinct on () 的 Sql Server,

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

但是在有很多列并且查询是临时查询的情况下,它会非常乏味去做。有简单的方法吗?

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_table

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

I could do in SQL Server:

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

But in cases where there are many columns and the query is an ad hoc one it is very tedious to do. Is there an easy way to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦醒灬来后我 2024-11-11 00:47:09

您可以尝试 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

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
岁吢 2024-11-11 00:47:09

除了接受的答案之外,您还可以避免使用两个句子并使用像这样的子选择

SELECT part.*
FROM (  SELECT *, ROW_NUMBER() OVER(PARTITION BY a ORDER BY b) Corr
    FROM my_table) part
WHERE part.Corr = 1

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文