How to get row column values as row headers in sql server
DECLARE @PivotColumnHeaders VARCHAR(MAX),
SELECT @PivotColumnHeaders = COALESCE(@PivotColumnHeaders + ',[' + cast(A.FieldName as varchar) + ']','[' + cast(A.FieldName as varchar)+ ']')
FROM dbo.tablename A -- where ID =5
print @PivotColumnHeaders
@SQLquery AS NVARCHAR(MAX);
SELECT @PivotColumnHeaders = COALESCE(@PivotColumnHeaders + ',[' + cast(A.FieldName as varchar) + ']','[' + cast(A.FieldName as varchar)+ ']')
FROM dbo.tablename A -- where ID =5
print @PivotColumnHeaders
set
@SQLquery
= 'SELECT date, ' +
@PivotColumnHeaders + ' from
(
select date
, amount
,
FieldName
from
dbo.tablename
) x
pivot
(
max(amount)
for
FieldName in (' + @cols + ')
) p '
execute(
@SQLquery
)
Comments
Post a Comment