Forum Discussion
SQL rows to collumns
Hi everyone,
I need your help.
I have a view that's return the result in this format:
but I need to have an output like this:
Does anyone have an idea on how to do it?
Thanks
- hi,
You can use this Query
SELECT Cod,ISNULL(ABF,0) ABF,ISNULL(SCA,0) SCA,ISNULL(SCC,0) SCC, ISNULL(MTV,0) MTV,ISNULL(PCP,0) PCP,ISNULL(SDT,0) SDT
FROM <YouTableName>
PIVOT
(
MAX(value) FOR Name in([ABF],[SCA],[SCC],[MTV],[PCP],[SDT])
)
as PivotTable
hope it'll work
Thanks
- Arshad440Brass Contributorhi,
You can use this Query
SELECT Cod,ISNULL(ABF,0) ABF,ISNULL(SCA,0) SCA,ISNULL(SCC,0) SCC, ISNULL(MTV,0) MTV,ISNULL(PCP,0) PCP,ISNULL(SDT,0) SDT
FROM <YouTableName>
PIVOT
(
MAX(value) FOR Name in([ABF],[SCA],[SCC],[MTV],[PCP],[SDT])
)
as PivotTable
hope it'll work
Thanks- Scorpion_S1Copper Contributor
Solved my problem.
I had already tried to make a Pivot Table but I wasn't getting the expected results. Thank you very much.
Since the 'name' column has variable values, I set up a query this way:
DECLARE @sql nvarchar(max);
DECLARE @fields varchar(max)
SELECT
@fields = COALESCE(@fields + ', ', '') + '[' + Name+ ']'
FROM (
SELECT DISTINCT name
FROM <TableName>
) field
SELECT @sql = N'
SELECT *
FROM <TableName>
PIVOT (
MAX(value)
FOR name IN
(' + @fields + ')
) AS PivotTable
'
EXEC sp_executesql @sql
Works as expected, just need to be able to put 0 instead of null.
Thanks once again.
- olafhelperBronze Contributor
Scorpion_S1 , see adtitional Using PIVOT and UNPIVOT - SQL Server | Microsoft Learn