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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Simple Distinction Question / Complex Answer?

Author  Topic 

man.olie
Starting Member

1 Post

Posted - 2010-09-09 : 11:00:55
First I want you to know that I am very grateful about your effort.
OK here it is:
Take this simple result set (a complex query thought with column/table aliases and several joins) that I have:

ColAlias1 ColAlias2 ColAlias3
1 EE Text1
2 EE Text2
3 EE Text3
1 BB Text4
2 BB Text5
3 BB Text6
4 BB Text7
3 GG Text8
4 GG Text9
....and so on
Simple, right???
Now I just want to get the rows which have different ColAlias2 values.
I don't care about the occurance order (it might be the first, the second, I don't care)

For example (first occurance of current order):
CA1 CA2 CA3
1 EE Text1
1 BB Text4
3 GG Text8

Any ideas?

MSquared
Yak Posting Veteran

52 Posts

Posted - 2010-09-09 : 11:18:09
I think this might be what you are looking for


declare @t table (
ColAlias1 smallint,
ColAlias2 varchar(2),
ColAlias3 varchar(5))

insert into @t
select 1, 'EE', 'Text1' Union all
select 2, 'EE', 'Text2' Union all
select 3, 'EE', 'Text3' Union all
select 1, 'BB', 'Text4' Union all
select 2, 'BB', 'Text5' Union all
select 3, 'BB', 'Text6' Union all
select 4, 'BB', 'Text7' Union all
select 3, 'GG', 'Text8' Union all
select 4, 'GG', 'Text9' union all
select 5, 'WW', 'Text0'


select t.ColAlias1, t.ColAlias2, t.ColAlias3
from @t t
inner join
(select ColAlias1, COUNT(distinct ColAlias2) NumRecords
from @t
group by ColAlias1
having COUNT(distinct ColAlias2) > 1) v
on t.ColAlias1 = v.ColAlias1


For Faster results please follow the posting guidelines here

http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx
Go to Top of Page
   

- Advertisement -