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 |
|
hiral265
Starting Member
1 Post |
Posted - 2010-01-11 : 14:22:58
|
| Hi,I have a table like this:Col1 Col2 Col31 2 A1 2 B1 2 C1 3 A1 3 B1 4 C1 5 AI want to insert rows in this table such that for every combination of col1 and col2, I have all distinct set of values of col3 i.e. my final table should look like:Col1 Col2 Col31 2 A1 2 B1 2 C1 3 A1 3 B1 3 C1 4 A1 4 B1 4 C1 5 A1 5 B1 5 CNotice that for every combination of col1 and col2 now I have 3 rows with A, B and C as the values in Col3.How do I achieve this with a query? And without using cursors.Any help would be greatly appreciated.Thanks |
|
|
shan
Yak Posting Veteran
84 Posts |
Posted - 2010-01-11 : 14:38:00
|
| Does this workdeclare @tbl as table (col1 varchar(2),col2 varchar(2), col3 varchar(2))insert into @tblselect '1','2','B'union allselect '1','2','C'union allselect '1','3','A'union allselect '1','3','B'union allselect '1','4','C'union allselect '1','5 ','A'select distinct col1,col2,B.col3 from @tbl Across apply(select col3 from @tbl ) as B-Shan |
 |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
|
webfred
Master Smack Fu Yak Hacker
8781 Posts |
Posted - 2010-01-11 : 14:38:59
|
[code]-- prepare testdatadeclare @yak table (col1 int, col2 int, col3 char(1))insert @yakselect 1, 2, 'A' union allselect 1, 2, 'B' union allselect 1, 2, 'C' union allselect 1, 3, 'A' union allselect 1, 3, 'B' union allselect 1, 4, 'C' union allselect 1, 5, 'A'-- show testdataselect * from @yak-- solution using testdatainsert @yakselect distinct y1.col1,y1.col2,y2.col3from @yak y1join(select distinct col3 from @yak) y2 on 1=1where not exists (select * from @yak where col1 = y1.col1 and col2 = y1.col2 and col3 = y2.col3 )-- show resultselect * from @yak order by col1,col2,col3[/code] No, you're never too old to Yak'n'Roll if you're too young to die. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2010-01-12 : 01:09:07
|
quote: Originally posted by hiral265 Hi,I have a table like this:Col1 Col2 Col31 2 A1 2 B1 2 C1 3 A1 3 B1 4 C1 5 AI want to insert rows in this table such that for every combination of col1 and col2, I have all distinct set of values of col3 i.e. my final table should look like:Col1 Col2 Col31 2 A1 2 B1 2 C1 3 A1 3 B1 3 C1 4 A1 4 B1 4 C1 5 A1 5 B1 5 CNotice that for every combination of col1 and col2 now I have 3 rows with A, B and C as the values in Col3.How do I achieve this with a query? And without using cursors.Any help would be greatly appreciated.Thanks
insert into tableselect t.col1,t1.col2,t2.col3from (select distinct col1,col2 from table)t1cross join (select distinct col3 from table)t2left join table t3on t1.col1=t3/col1and t1.col2=t3.col2and t2.col3=t3.col3where t3.col1 is null |
 |
|
|
|
|
|
|
|