我正在尝试查询 sybase 服务器以获取我们出于测试目的而保存的不同类型数据的示例。
我有一张如下所示的表格(摘要)
Animals table:
id | type | breed | name
------------------------------------
1 | dog | german shepard | Bernie
2 | dog | german shepard | James
3 | dog | husky | Laura
4 | cat | british blue | Mr Fluffles
5 | cat | other | Laserchild
6 | cat | british blue | Sleepy head
7 | fish | goldfish | Goldie
正如我提到的,我想要每种类型的示例,因此对于上表,我想要一个如下结果集(实际上我只想要 ID):
id | type | breed
---------------------------
1 | dog | german shepard
3 | dog | husky
4 | cat | british blue
5 | cat | other
7 | fish | goldfish
我已经尝试了多种查询组合,如下所示,但它们要么是无效的 SQL(对于 sybase),要么返回无效的结果
SELECT id, DISTINCT ON type, breed FROM animals
SELECT id, DISTINCT(type, breed) FROM animals
SELECT id FROM animals GROUP BY type, breed
我发现了其他问题,例如在一列上选择 DISTINCT https://stackoverflow.com/questions/966176/select-distinct-on-one-column但这只处理一列
您知道如何实现此查询吗?
也许你必须使用聚合函数max
or min
对于列 ID。它将仅返回分组列的一个 ID。
select max(Id), type, breed
from animals
group by type, breed
EDIT:
其他不同的方法来做到这一点:
具有聚合函数
select id, type, breed
from animals
group by type, breed
having id = max(Id)
使用having和聚合子查询
select id, type, breed
from animals a1
group by type, breed
having id = (
select max(id)
from animals a2
where a2.type = a1.type
and a2.breed = a1.breed
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)