There is nice article on MSDN which explains how to PIVOT or UNPIVOT with examples. Below is an example of PIVOTing your table.
SELECT *
FROM (
SELECT Vendor,
ConsultantID,
Billrate
FROM #PVT
) as t
pivot
(
MAX(Billrate) FOR ConsultantID in ([1],[2],[3],[4],[5])
) as pvt
Output:
Vendor 1 2 3 4 5
Bridge Consulting 95,00 90,00 104,00 103,00 100,00
ChinaSoft Consulting 108,00 115,00 125,00 130,00 120,00
Excell Data 140,00 143,00 140,00 145,00 200,00
TekSystem Consulting 110,00 120,00 130,00 220,00 230,00
Volt Consulting 100,00 180,00 200,00 120,00 240,00
In this sample we know that there will be 5 column headers. If you have no idea how many there are - you must use dynamic SQL:
DECLARE @columns nvarchar(max),
@sql nvarchar(max)
--Here we get [1],[2],[3],[4],[5] in the @columns variable to use in dynamic query
SELECT @columns = STUFF(
(SELECT DISTINCT ','+QUOTENAME(ConsultantID)
FROM #PVT
FOR XML PATH ('')),1,1,'')
SET @sql =
'SELECT *
FROM (
SELECT Vendor,
ConsultantID,
Billrate
FROM #PVT
) as t
pivot
(
MAX(Billrate) FOR ConsultantID in ('+@columns+')
) as pvt'
EXEC (@sql)
Output will be the same.
EDIT
If you want to add totals by Vendor or by Consultants use this (works in SQL Server 2008 and up):
;WITH cte AS (
SELECT *, [1]+[2]+[3]+[4]+[5] as Totals
FROM (
SELECT Vendor,
ConsultantID,
Billrate
FROM #PVT
) as t
pivot
(
MAX(Billrate) FOR ConsultantID in ([1],[2],[3],[4],[5])
) as pvt
)
SELECT *
FROM cte
UNION ALL
SELECT 'Total',SUM([1]),SUM([2]),SUM([3]),SUM([4]),SUM([5]), NULL as Totals
FROM cte
For dynamic:
DECLARE @columns nvarchar(max),
@sql nvarchar(max)
SELECT @columns = STUFF(
(SELECT DISTINCT ','+QUOTENAME(ConsultantID)
FROM #PVT
FOR XML PATH ('')),1,1,'')
SET @sql =
';WITH cte AS (
SELECT *, ' + REPLACE(@columns,',','+') +' as Totals
FROM (
SELECT Vendor,
ConsultantID,
Billrate
FROM #PVT
) as t
pivot
(
MAX(Billrate) FOR ConsultantID in ('+@columns+')
) as pvt
)
SELECT *
FROM cte
UNION ALL
SELECT ''Total'',SUM(' + REPLACE(@columns,',','),SUM(') + '), NULL as Totals
FROM cte
'
EXEC (@sql)
Output:
Vendor 1 2 3 4 5 Totals
Bridge Consulting 95,00 90,00 104,00 103,00 100,00 492,00
ChinaSoft Consulting 108,00 115,00 125,00 130,00 120,00 598,00
Excell Data 140,00 143,00 140,00 145,00 200,00 768,00
TekSystem Consulting 110,00 120,00 130,00 220,00 230,00 810,00
Volt Consulting 100,00 180,00 200,00 120,00 240,00 840,00
Total 553,00 648,00 699,00 718,00 890,00 NULL