2

I got a table with Cities and States it looks something like:

cityid    |city    |stateid    |state
--------------------------------------
0566      |abriaqui|05         |antioquia
0599      |alejand |05         |antioquia
0511      |another |05         |antioquia
0782      |dummy1  |09         |caldas
0783      |dummy2  |09         |caldas
0785      |dummy3  |09         |caldas
0788      |dummy4  |03         |Narino
0767      |dummy5  |03         |Narino
0734      |dummy6  |03         |Narino

As you can see I have Cities with uniques IDs, and the state they belong to is just to the right, with the state id and the state name. I would like to make a query that returns something similar to DINSTINCT(state):

STATE
--------------------
antioquia
caldas
narino

But I need the stateid too. How can I reach this?

halfer
  • 19,824
  • 17
  • 99
  • 186
JuanBonnett
  • 776
  • 3
  • 8
  • 26
  • which engine + give a proper expected resulset. Rigorous questions give rigorous results, and the contrary too. – Sebas Jul 23 '13 at 14:01

5 Answers5

2

Try this way:

select distinct state, stateid
from tab

you can also use group by clause

select state, stateid
from tab
group by state, stateid

Group by is useful if you need some aggregation function. Solution is depend of your requirements.

Robert
  • 25,425
  • 8
  • 67
  • 81
2

Just do something like this:

SELECT DISTINCT state, stateid
FROM table
DarkAjax
  • 15,955
  • 11
  • 53
  • 65
  • 1
    I feel bad now that I see it was that easy... I mean, I was trying to use DISTINCT (sate, stateid) with PARENTESIS... May be that's why it wouldn't work. Thank you! – JuanBonnett Jul 23 '13 at 14:08
  • @JuanBonnett don't worry just try reading the documentation for whatever DBMS you're using next time you have a doubt or are unsure of the syntax, believe me it helps a lot! :) – DarkAjax Jul 23 '13 at 14:10
1

Have you tried this?

select distinct stateid, state
from CityStates cs
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1
Select Distinct stateid, state  
from myTable
Hedinn
  • 864
  • 4
  • 7
1

You should rearrange your database to store states in separate table STATES(id, name) and CITIES(id, name, state_id), then for selecting states you can use

SELECT id, name from STATES
VitaliyG
  • 1,837
  • 1
  • 11
  • 11