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 |
|
Kervin
Starting Member
12 Posts |
Posted - 2005-08-10 : 01:26:16
|
| How can I go about getting a result set that is distinct on only one field and still get the information from the other fields without looping:If I have a table with primary_key, first_name,last_name1,joe,smith2,bob,smith3,fred,smith4,joe,green5,fred,greenI want to do something likeSELECT (DISTINCT last_name),first_name,primary_key FROM tableI want a way to get the DISTINCT to only look at the last_name field not all fields when filtering the results but still create a record set that contains the last_name, first_name and the primary key?in the example above I want a results set like thisprimary_key, first_name,last_name1,joe,smith4,joe,greenthanks.ThankxKervin.kervin_findlay@hotmail.com |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2005-08-10 : 01:30:51
|
| Try thisSelect Distinct (select top 1 primary_key from yourtable where last_name=T.last_name),(select top 1 first_name from yourtable where last_name=T.last_name),last_name from yourtable TMadhivananFailing to plan is Planning to fail |
 |
|
|
Kervin
Starting Member
12 Posts |
Posted - 2005-08-10 : 01:58:41
|
| Thank you.I dont claim to understand all of the logic behind it, but it does exactly what I need. The example I gave was very simplified compared to what I am actually doing but this will help me in a number of situations where I need to use DISTINCT in this way... I hope it doesn't slow down too much on a larger results set - but it does the trick right now. :-)ThankxKervin.kervin_findlay@hotmail.com |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2005-08-10 : 02:13:50
|
| >> hope it doesn't slow down too much on a larger results set I think it will slow down the performance if there are millions of dataAs an alternative try this alsoSelect * from yourtableWhere primary_key in (select min(primary_key) from yourtable group by last_name)MadhivananFailing to plan is Planning to fail |
 |
|
|
Kervin
Starting Member
12 Posts |
Posted - 2005-08-10 : 02:50:38
|
| That is much cleaner.Thank you for you help.ThankxKervin.kervin_findlay@hotmail.com |
 |
|
|
|
|
|
|
|