Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Nest a PIVOT query in an outer query

Status
Not open for further replies.

waubain

Technical User
Dec 13, 2011
200
US
I have pivoted some data using the following sql.

SQL:
USE TEST
DECLARE @sql AS varchar(MAX)
DECLARE @columns AS varchar(MAX)

SELECT @columns = 
	COALESCE(@columns + ',','') + QUOTENAME(RowID)
FROM
(
SELECT DISTINCT RowID
FROM [dbo].[DateOfBirth]
) AS B
ORDER BY B.RowID

SET @sql = '
WITH PivotData AS
(
SELECT *
FROM [dbo].[DateOfBirth]
) 
SELECT
ID
,'+ @columns +'
FROM PivotData
PIVOT
(
MAX(DateOfBirth)
FOR RowID
IN (' + @columns + ')
) AS PivotResult
ORDER BY ID'

EXEC(@sql)

I now want to compare columns in an outer query, but my usual structure does not work.

SQL:
USE TEST
DECLARE @sql AS varchar(MAX)
DECLARE @columns AS varchar(MAX)

SELECT *
     ,CASE(.....
FROM
(
SELECT @columns = 
	COALESCE(@columns + ',','') + QUOTENAME(RowID)
FROM
(
SELECT DISTINCT RowID
FROM [dbo].[DateOfBirth]
) AS B
ORDER BY B.RowID

SET @sql = '
WITH PivotData AS
(
SELECT *
FROM [dbo].[DateOfBirth]
) 
SELECT
ID
,'+ @columns +'
FROM PivotData
PIVOT
(
MAX(DateOfBirth)
FOR RowID
IN (' + @columns + ')
) AS PivotResult
ORDER BY ID'

EXEC(@sql)
)
AS C

Any suggestions would be appreciated

You don't know what you don't know...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top