SQl server query problem only a pro can help :(

Discussion in 'Databases' started by ezguy, Jul 21, 2007.

  1. #1
    I have a table called table1

    it has fields

    Id
    Cityname

    records

    1 - miami
    2 - miami
    3 - miami
    4 - orlando
    5 - orlando
    6 - miami


    I want to do a query on the records

    it should return only distinct city with ID

    iam using this

    select distinct cityname,id from table1

    but the results return all the records. I want city name to be distinct at the same time also give the id for the cityname

    how to solve this

    can some one help :(
     
    ezguy, Jul 21, 2007 IP
  2. ecentricNick

    ecentricNick Peon

    Messages:
    351
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Well, really it depends on which id you want returned against each city - but...

    Select Cityname,Min(Id)
    From table1
    Group by Cityname

    Should give you...

    Miami,1
    Orlando,4

    Coversely...
    Select Cityname,Max(Id)
    From table1
    Group by Cityname

    Should give you...

    Miami,6
    Orlando,5

    But, if you ask me, it's a pretty silly table structure - you're breaking every normalisation rule and sooner or later, it's gonna bite you.
     
    ecentricNick, Jul 21, 2007 IP
  3. ezguy

    ezguy Well-Known Member

    Messages:
    1,184
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    128
    #3
    hey thanks it worked :)
     
    ezguy, Jul 21, 2007 IP
  4. qazu

    qazu Well-Known Member

    Messages:
    1,834
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    165
    #4
    If those two fields are the only fields in the table I'd put a unique constraint on Cityname. They there would be no problem with your original query.
     
    qazu, Jul 22, 2007 IP