我正在尝试查询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
我发现了其他问题,例如SELECT DISTINCT on one column,但这只涉及一列
您是否知道如何实施此查询?
答案 0 :(得分:2)
也许您必须对列ID使用聚合函数max
或min
。它只会为分组列返回一个ID。
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
)
答案 1 :(得分:-1)