gpt4 book ai didi

sql - 使用 Postgres 从每组中取出一个对象

转载 作者:行者123 更新时间:2023-11-29 14:34:19 25 4
gpt4 key购买 nike

我正在处理一张猫表,并尝试编写一条语句,从每个年龄组中选择一只猫。

这是我的 table

pets=# SELECT * FROM cats;
id | name | gender | age | intake_date | adoption_date
----+----------+--------+-----+---------------------+---------------------
1 | Mushi | M | 1 | 2016-01-09 00:00:00 | 2016-03-22 00:00:00
2 | Seashell | F | 7 | 2016-01-09 00:00:00 |
3 | Azul | M | 3 | 2016-01-11 00:00:00 | 2016-04-17 00:00:00
4 | Victoire | M | 7 | 2016-01-11 00:00:00 | 2016-09-01 00:00:00
5 | Nala | F | 1 | 2016-01-12 00:00:00 |
(5 rows)

最佳答案

使用distinct on:

select distinct on (c.age) c.*
from cats c
order by age;

关于sql - 使用 Postgres 从每组中取出一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47293557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com