I'm using SQL 2008. I want to essentially turn rows into columns. The source table has a variable number of rows and a fixed number of columns - the magical, elusive SQL query will yield a result that has a variable number of columns and fixed number of rows. A slight twist is that there is grouping by Territory, and in this example the first two rows should be reduced to one, with the SlsPerson concatenated to AA/BB.The table, represented by RC_DataTable:Territory----State--Est--SlsPerson----------------------------------Chicago------IL-----2004--AA------Chicago------IL-----2004--BB------New York-----NY-----1989--CC------Los Angeles--CA-----2007--DD------The result of the query will yield:COL1------COL2-------COL3---------------------------------------------Chicago---New York---Los Angeles---IL--------NY---------CA------------2004------1989-------2007----------AA/BB-----CC---------DD------------
Here is a script to establish the above data:USE [Northwind]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[RCDataTable]( [Territory] [varchar](20) NULL, [State] [varchar](2) NULL, [Established] [varchar](4) NULL, [Salesperson] [varchar](50) NULL) ON [PRIMARY]GOSET ANSI_PADDING OFFGOINSERT [dbo].[RCDataTable] ([Territory], [State], [Established], [Salesperson]) VALUES (N'Chicago', N'IL', N'2004', N'AA')INSERT [dbo].[RCDataTable] ([Territory], [State], [Established], [Salesperson]) VALUES (N'Chicago', N'IL', N'2004', N'BB')INSERT [dbo].[RCDataTable] ([Territory], [State], [Established], [Salesperson]) VALUES (N'New York', N'NY', N'1989', N'CC')INSERT [dbo].[RCDataTable] ([Territory], [State], [Established], [Salesperson]) VALUES (N'Los Angeles', N'CA', N'2007', N'DD')