pivot in sql server query code example

Example 1: sql pivot

SELECT *        -- Total invoices per gender
FROM (
    SELECT invoice, gender
    FROM sales
) d
PIVOT (
    sum(invoice)
    FOR gender IN ('F' AS "Women", 'M' AS "Men")
);
-- Table Sales:
CREATE TABLE sales (
    gender VARCHAR2(1 BYTE),		-- 'F' or 'M'
    invoice NUMBER
);

Example 2: sql server pivot rows to columns

-- Dynamic Pivot with unknown number of columnnames

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;

Tags:

Sql Example