我正在尝试查询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
您知道如何实现此查询吗?
也许您必须使用聚合函数max或min用于列ID。对于分组的列,它将仅返回一个ID。
max
min
select max(Id), type, breed from animals group by type, breed
编辑:
其他不同的执行方式:
具有汇总功能
select id, type, breed from animals group by type, breed having id = max(Id)
具有和聚合子查询
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 )