Sybase SQL Select Distinct Based on Multiple Columns with an ID

≯℡__Kan透↙ 提交于 2019-12-12 15:36:02

问题


I'm trying to query a sybase server to get examples of different types of data we hold for testing purposes.

I have a table that looks like the below (abstracted)

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

As I mentioned I want an example of each type so for the above table would like a results set like (in reality I just want the ID's):

id | type | breed           
---------------------------
1  | dog  | german shepard  
3  | dog  | husky          
4  | cat  | british blue   
5  | cat  | other          
7  | fish | goldfish    

I've tried multiple combinations of queries such as the below but they are either invalid SQL (for sybase) or return invalid results

  SELECT id, DISTINCT ON type, breed FROM animals
  SELECT id, DISTINCT(type, breed) FROM animals
  SELECT id FROM animals GROUP BY type, breed

I've found other questions such as SELECT DISTINCT on one column but this only deal with one column

Do you have any idea how to implement this query?


回答1:


Maybe you have to use aggregate function max or min for column ID. It will return only one ID for grouped columns.

select max(Id), type, breed 
from animals
group by type, breed 

EDIT:

Other different ways to do it:

With having and aggregate function

select id, type, breed  
from animals 
group by type, breed  
having id = max(Id)

With having and aggregate subquery

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
            )



回答2:


Try this and let me know if it works:

select distinct breed, max(id) as id , max(type) as type
from animals

You may have to play around with max() The arbitrary choice here is max(), but you could arbitrarily use min() instead. max() returns the largest value for that columns, min() the smallest



来源:https://stackoverflow.com/questions/12368754/sybase-sql-select-distinct-based-on-multiple-columns-with-an-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!