Dynamic Pivot on Single Column in a Table Sql Server 2008
create table Pivot_Example(col1 varchar(200))
insert into Pivot_Example values('A'),('B'),('C'),('D')
select * from Pivot_Example
DECLARE @query VARCHAR(4000)
DECLARE @years VARCHAR(2000)
SELECT @years = STUFF((SELECT '],[' + ltrim(col1)
FROM Pivot_Example
ORDER BY '],[' + ltrim(col1)
FOR XML PATH('')
), 1, 2, '') + ']'
select @years
SET @query =
'SELECT * FROM
(
SELECT top 0 *,row_number() over(order by col1) amount
FROM Pivot_Example
)t
PIVOT (max(amount) FOR col1
IN ('+@years+')) AS pvt'
EXECUTE (@query)
insert into Pivot_Example values('A'),('B'),('C'),('D')
select * from Pivot_Example
DECLARE @query VARCHAR(4000)
DECLARE @years VARCHAR(2000)
SELECT @years = STUFF((SELECT '],[' + ltrim(col1)
FROM Pivot_Example
ORDER BY '],[' + ltrim(col1)
FOR XML PATH('')
), 1, 2, '') + ']'
select @years
SET @query =
'SELECT * FROM
(
SELECT top 0 *,row_number() over(order by col1) amount
FROM Pivot_Example
)t
PIVOT (max(amount) FOR col1
IN ('+@years+')) AS pvt'
EXECUTE (@query)
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment