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 |
rgombina
Constraint Violating Yak Guru
319 Posts |
Posted - 2008-11-24 : 06:16:40
|
Hi again,I would like to pivot the data and would like some help please...Data:ID Col1 Col21 val1 newval11 val2 newval21 val31 val4I would like to make multiple rows if number of rows reached. So here's what I am hoping to get:ID Col1 Col21 val1 newval11 val2 newval21 val3 newval1 <- repopulated1 val4 newval2 <- repopulatedBasically, if Col1 reaches greater than 2 rows from the same ID, then new rows created with Col2 repopulated.Thanks again... |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2008-11-24 : 06:32:57
|
[code]DECLARE @Sample TABLE ( ID INT, col1 VARCHAR(20), col2 VARCHAR(20) )INSERT @Sample ( ID, col1, col2 )SELECT 1, 'col1', 'newval1' UNION ALLSELECT 1, 'col2', 'newval2' UNION ALLSELECT 1, 'col3', NULL UNION ALLSELECT 1, 'col4', NULLSELECT *FROM @SampleDECLARE @Found TABLE ( rowID INT IDENTITY(0, 1) PRIMARY KEY CLUSTERED, col2 VARCHAR(20) )DECLARE @Items INTINSERT @Found ( col2 )SELECT col2FROM @SampleWHERE col2 IS NOT NULLORDER BY col1SET @Items = @@ROWCOUNTDECLARE @Missing TABLE ( rowID INT IDENTITY(0, 1) PRIMARY KEY CLUSTERED, col1 VARCHAR(20), col2 VARCHAR(20) )INSERT @Missing ( col1, col2 )SELECT col1, col2FROM @SampleWHERE col2 IS NULLORDER BY col1UPDATE sSET s.col2 = z.col2FROM @Sample AS sINNER JOIN ( SELECT m.col1, f.col2 FROM @Found AS f INNER JOIN @Missing AS m ON m.rowID % @Items = f.rowID ) AS z ON z.col1 = s.col1SELECT *FROM @Sample[/code] E 12°55'05.63"N 56°04'39.26" |
|
|
rgombina
Constraint Violating Yak Guru
319 Posts |
Posted - 2008-11-24 : 06:37:33
|
Wow Peso, thanks for a very quick reply! I really appreciate it. |
|
|
|
|
|
|
|