Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help formulating difficult query

Status
Not open for further replies.

etones

Programmer
Mar 7, 2002
9
0
0
GB
First I will give an example of the table in question.

id | country | inuse | reference
------------------------------------------------
1 | UK | 1 | 44
2 | UK | 1 | 514
3 | UK | 0 | 221
4 | USA | 1 | 993
5 | USA | 0 | 472
6 | USA | 1 | 092

I want to write a query that will list every distinct country and will also list any one id along with it. Here is an example of what i would like produced.

id | country
-------------------
1 | UK
4 | USA

The way i do it at the moment is to issue:
select distict country from table

And then i do the following for every country produced above:

select id from table where country='countryname' limit 1

I'm sure there is a quicker way to do this but I just cannot find it.
Hope somebody can help.

 
You can use SELECT DISTINCT ON instead of SELECT DISTINCT and specify the field to use it on.

SELECT DISTINCT ON (country) id, country
FROM mytable
WHERE country = 'UK';

The field that you use the DISTINCT ON modifier on must be listed in parentheses before your list of the fields.
 
Thanks!
I didn't realize you could add the 'ON' to the DISTINCT statement.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top