pivot columns to rows sql code example
Example 1: sql server pivot rows to columns
select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
select value, columnname
from yourtable
) d
pivot
(
max(value)
for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;
Example 2: sql pivot rows to columns
SELECT *
FROM (
SELECT invoice, gender
FROM sales
) d
PIVOT (
sum(invoice)
FOR gender IN ('F' AS "Women", 'M' AS "Men")
);
CREATE TABLE sales (
gender VARCHAR2(1 BYTE),
invoice NUMBER
);
Example 3: sql server pivot rows to columns
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName)
from yourtable
group by ColumnName, id
order by id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select value, ColumnName
from yourtable
) x
pivot
(
max(value)
for ColumnName in (' + @cols + N')
) p '
exec sp_executesql @query;