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 |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2003-03-10 : 07:22:29
|
| Kalyan writes "I need to query a table and return only one record for each distinct value in a column. Consider the following people table example:FirstName LastName Address City State--------- -------- ------- ---- -----John Bradley 1 Test NoWhere MDJill Bradley 10 Test NoWhere MDTom Hayworth 2 Test NoWhere MD*********************************The query when tested for records with distinct last names should return one of the following set of records:John Bradley 1 Test NoWhere MDTom Hayworth 2 Test NoWhere MDorJill Bradley 10 Test NoWhere MDTom Hayworth 2 Test NoWhere MD*********************************That is, it should return a representative record for every value in the specified column.Can someone help me how to do this?Thanks," |
|
|
joldham
Wiseass Yak Posting Master
300 Posts |
Posted - 2003-03-10 : 07:58:43
|
| Well that all depends on which dataset you want to return.You sould use something like the following:Select b.FirstName, a.LastName, b.Address, b.City, b.StateFrom (Select LastName, Max(Address) as AddressFrom myTableGROUP BY FirstName, LastName) aINNER JOIN myTable band a.LastName = b.LastNameand a.Address = b.AddressThe Max(address) part of the query in this case would return the '10 Test' and 'John' record for the Bradley last name. If you changed this to Min(Address) then it would return the '1 Test' and 'Jill' record for the Bradley last name.Hope this helps.Jeremy |
 |
|
|
|
|
|