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 |
|
scozzese
Starting Member
12 Posts |
Posted - 2004-02-06 : 09:28:48
|
| I have the following table "MyTable" with records:Field.Code Field.Q_ty Field.CellA 10 1A 12 2B 15 1B 9 2B 13 3Now I need help to create a query with multiple columns for Field.Cell. The number of column Field.Q_ty_Cell_? must be the same of the record that result from:SELECT DISTINCT Field.Cell FROM MyTaBLEAt the end I'll expect the following result:Field.Code Field.Q_ty_Cell_1 Field.Q_ty_Cell_2 Field.Q_ty_Cell_3A 10 12 0B 15 9 13 Thankyou for help.Roberto |
|
|
AndyB13
Aged Yak Warrior
583 Posts |
Posted - 2004-02-06 : 09:44:13
|
| You want a pivot table then?These 2 articles should get you started[url]http://www.sqlteam.com/item.asp?ItemID=2955[/url][url]http://www.sqlteam.com/item.asp?ItemID=5741[/url] |
 |
|
|
ditch
Master Smack Fu Yak Hacker
1466 Posts |
Posted - 2004-02-07 : 14:33:56
|
This should work if 'MyTable' isn't too large--*******************************************************************DECLARE @Code VarChar(1)DECLARE @Qty INTDECLARE @Cell INTDECLARE @MaxCols INTDECLARE @CreateTableSQL VARCHAR(1000)DECLARE @InsertTableSQL VARCHAR(1000)DECLARE @UpdateSQL VARCHAR(1000)DECLARE @SelectSQL VARCHAR(1000)DECLARE @ColCT INTSET @MaxCols = (SELECT MAX(ColCT) FROM (SELECT Code, COUNT(Qty) ColCT FROM MyTable GROUP BY Code) as A)SET @CreateTableSQL = 'CREATE TABLE #Results(Code VARCHAR(1)'SET @InsertTableSQL = 'INSERT INTO #Results SELECT DISTINCT Code'SET @ColCT = 1WHILE @ColCT <= @MaxColsBEGIN SET @CreateTableSQL = @CreateTableSQL + ', Qty_' + RIGHT('000' + RTRIM(LTRIM(STR(@ColCT, 3))), 3) + ' Int' SET @InsertTableSQL = @InsertTableSQL + ', 0' SET @ColCT = @ColCT + 1ENDSET @CreateTableSQL = @CreateTableSQL + ') 'SET @InsertTableSQL = @InsertTableSQL + ' FROM MyTable 'SET @UpdateSQL = ''DECLARE MyCurCURSOR FORSELECT Code, Qty, CellFROM MyTableORDER BY Code, Qty, CellOPEN MyCurFETCH NEXT FROM MyCurINTO @Code, @Qty, @CellWHILE @@FETCH_STATUS = 0BEGIN SET @UpdateSQL = @UpdateSQL + ' UPDATE #Results SET ' + ' QTY_' + RIGHT('000' + RTRIM(LTRIM(STR(@Cell, 3))), 3) + ' = ' + STR(@Qty, 3) + ' WHERE Code = ''' + @Code + '''; ' FETCH NEXT FROM MyCur INTO @Code, @Qty, @CellENDCLOSE MyCurDEALLOCATE MyCurEXEC(@CreateTableSQL + @InsertTableSQL + @UpdateSQL + ' SELECT * FROM #Results' )--*******************************************************************I'm sure that some of the other yakkers have got better ways to do this though |
 |
|
|
|
|
|
|
|