Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Champinco
Yak Posting Veteran
54 Posts |
Posted - 2006-11-19 : 19:34:16
|
Hi guys i need help with thisCode NameNULL MobileNULL UNSPECIFIED10 COMMUNICATIONS10 COMMUNICAITONS10 OFFICE COMMSHow do I select distinct codes, with the corresponding name (the 1st one or 2nd-doesn’t matter which one).I.E:I want this result:Code NameNULL Mobile10 COMMUNICATIONSI tried select distinct Code, Name,from tableBut obviously this doesn’t work as Name column has different words in it.CheersGK |
|
snSQL
Master Smack Fu Yak Hacker
1837 Posts |
Posted - 2006-11-19 : 19:51:20
|
quote: (the 1st one or 2nd-doesn’t matter which one).
It does matter, which is why SQL Server doesn't guess. So you can pick one using whichever aggregate function you like, for exampleSELECT Code, min([Name])FROM tableGROUP BY Code |
 |
|
Champinco
Yak Posting Veteran
54 Posts |
Posted - 2006-11-19 : 22:03:43
|
yes sorry this is obvious.what i should of also indicated was that i have another column with a dollar value in it such that i cannot use a group by: i.e:Amount Code Name$30.55 1075 21ST CENTURY COMMUNICATION$30.55 1075 CENTURY COMMUNICATION$11.52 2921 A & B COMMUNICATIONS$1934.26 5012 A & P ELECTRONICS - LET$6.20 4073 A CUMMINGS & CO$6.20 4073 CUMMINGS & CO$6.20 4073 CUMMINGS and COSuch that I keep only one record that has the same code and amount, and choose the 1st or 2nd (or 3rd etc...) name. in this scenario:Amount Code Name$30.55 1075 21ST CENTURY COMMUNICATION$11.52 2921 A & B COMMUNICATIONS$1934.26 5012 A & P ELECTRONICS - LET$6.20 4073 A CUMMINGS & CODo I use some sort of count that goes through each row systematically?CheersGK |
 |
|
snSQL
Master Smack Fu Yak Hacker
1837 Posts |
Posted - 2006-11-19 : 23:25:33
|
Are the amounts always the same? You really should clean up the data otherwise you'll start getting all sorts of problems, but if the amount is the same for the same code then you can use min for the amount tooSELECT Code, min([Name]), min(Amount)FROM tableGROUP BY Code |
 |
|
|
|
|