Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Give this table of data:ID1 | ID2 | Type-------------------------3 | 5 | A3 | 5 | B4 | 7 | A4 | 7 | BI want to select distinct ID1 and ID2 pairs, and when there are dups, grab the value for Type randomly.So one select could result in:3 - 5 - A4 - 7 - Band another select could result in:3 - 5 - B4 - 7 - BIf I had a random aggregate it would be easy:select ID1, ID2, random(Type) as Typefrom ordersgroup by ID1, ID2but we don't have one, so there must be something I can do insteadThanks!Daniel
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2007-06-03 : 01:29:48
how about this ?
declare @table table( ID1 int, ID2 int, Type char(1))insert into @tableselect 3, 5, 'A' union allselect 3, 5, 'B' union allselect 4, 7, 'A' union allselect 4, 7, 'B' union allselect 5, 7, 'C'select ID1, ID2, Type = case when count(*) > 1 then (select top 1 Type from @table x where x.ID1 = t.ID1 and x.ID2 = t.ID2 order by newid()) else max(Type) endfrom @table tgroup by ID1, ID2
KH
coldfusioner
Starting Member
2 Posts
Posted - 2007-06-03 : 01:49:56
Brilliant!
madhivanan
Premature Yak Congratulator
22864 Posts
Posted - 2007-06-09 : 07:35:32
Isnt this enough?
select ID1, ID2, Type = (select top 1 Type from @table x where x.ID1 = t.ID1 and x.ID2 = t.ID2 order by newid())from @table t