1SELECT * -- Total invoices per gender
2FROM (
3 SELECT invoice, gender
4 FROM sales
5) d
6PIVOT (
7 sum(invoice)
8 FOR gender IN ('F' AS "Women", 'M' AS "Men")
9);
10-- Table Sales:
11CREATE TABLE sales (
12 gender VARCHAR2(1 BYTE), -- 'F' or 'M'
13 invoice NUMBER
14);
1select Firstname, Amount, PostalCode, LastName, AccountNumber
2from
3(
4 select value, columnname
5 from yourtable
6) d
7pivot
8(
9 max(value)
10 for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
11) piv;
1select *
2from
3(
4 select game, player, goals
5 from yourtable
6) src
7pivot
8(
9 sum(goals)
10 for player in ([John], [Paul], [Mark], [Luke])
11) piv
12order by game
13
1SELECT SalesAgent AS PivotSalesAgent, India, US, UK FROM tblAgentsSales
2PIVOT
3(
4 SUM(SalesAmount) FOR SalesCountry IN (India, US, UK)
5)
6AS testPivotTable
7
8
9SELECT SalesAgent GrpBySalesAgent, SalesCountry, SUM(SalesAmount) Sales
10from tblAgentsSales
11GROUP BY SalesAgent, SalesCountry
12
13
14select SalesAgent TableSalesAgent, SalesCountry, SalesAmount
15from tblAgentsSales
1SELECT SalesAgent AS PivotSalesAgent, India, US, UK FROM tblAgentsSales
2PIVOT
3(
4 SUM(SalesAmount) FOR SalesCountry IN (India, US, UK)
5)
6AS testPivotTable
7
8
9SELECT SalesAgent GrpBySalesAgent, SalesCountry, SUM(SalesAmount) Sales from tblAgentsSales
10GROUP BY SalesAgent, SalesCountry
11
12
13select SalesAgent TableSalesAgent, SalesCountry, SalesAmount from tblAgentsSales
1-- Dynamic Pivot with unknown number of columnnames
2
3DECLARE @cols AS NVARCHAR(MAX),
4 @query AS NVARCHAR(MAX)
5
6select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName)
7 from yourtable
8 group by ColumnName, id
9 order by id
10 FOR XML PATH(''), TYPE
11 ).value('.', 'NVARCHAR(MAX)')
12 ,1,1,'')
13
14set @query = N'SELECT ' + @cols + N' from
15 (
16 select value, ColumnName
17 from yourtable
18 ) x
19 pivot
20 (
21 max(value)
22 for ColumnName in (' + @cols + N')
23 ) p '
24
25exec sp_executesql @query;