Dynamic Pivot on Single Column in a Table Sql Server 2008
undefined
undefined
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)
- SSIS Logging Table Customizing
- Getting column description and Update descriptions in SQL Server
- SQL SERVER Start and Stop services Using SSIS
- SQL Server log shrinking Issue
- Dynamic Pivot on Single Column in a Table Sql Server 2008
- Run same command on all SQL Server databases without cursors
- SQL SERVER – ReIndexing Database Tables and Update Statistics on Tables
- Delete Original Data and maintain history with single SQl statement......(Magic tables)
- SQL Server Recursive CTE
- SQL Server Advanced Queries
- Which index will SQL Server use to count all rows
- SQL Server Performance Tips
- Sql Server Temporary Tables vs Table Variables
- Differences between sqlserver 2000, 2005 and 2008 versions
- SSIS Interview Quesions and Answers
0 comments:
Post a Comment