在 Postgres 中为每个组选择任意行

发布于 2025-01-14 16:40:00 字数 591 浏览 1 评论 0原文

在 Presto 中,有一个 任意() 聚合函数来选择给定组中的任意行。如果没有group by子句,那么我可以使用distinct on。使用 group by 时,每个选定的列都必须位于 group by 中或者是聚合列。例如:

| id | foo |
| 1  | 123 |
| 1  | 321 |

select id, arbitrary(foo), count(*)
from mytable
group by id

Fiddle

返回1也没关系, 123, 21, 321, 2。像 min()max() 这样的方法可以工作,但速度要慢得多。

Postgres 中是否存在类似 argumentary() 的东西?

In Presto, there's an arbitrary() aggregate function to select any arbitrary row in a given group. If there's no group by clause, then I can use distinct on. With group by, every selected column must be in the group by or be an aggregated column. E.g.:

| id | foo |
| 1  | 123 |
| 1  | 321 |

select id, arbitrary(foo), count(*)
from mytable
group by id

Fiddle

It doesn't matter if it returns 1, 123, 2 or 1, 321, 2. Something like min() or max() works, but it's a lot slower.

Does something like arbitrary() exist in Postgres?

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

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

发布评论

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

评论(1

长亭外,古道边 2025-01-21 16:40:00
select  m.foo,b.id,b.cnt from mytable m  
join (select id, count(*) cnt
from mytable
group by id) b  using (id)  limit 1;

如果没有明确提及ascdesc,则无法保证所有顺序。因此在上面的查询中 foo 的出现是任意的。

select  m.foo,b.id,b.cnt from mytable m  
join (select id, count(*) cnt
from mytable
group by id) b  using (id)  limit 1;

If not explicit mention asc, desc all the order is not guaranteed. Therefore in the above query the foo's appearance is arbitrary.

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