CREATE TABLE Test
(Department varchar (10),
Customer varchar (10),
Cost name varchar (10),
Amount int)
INSERT into test values (' A ', ' a ', ' phone fee ', 10)
INSERT into test values (' A ', ' a ', ' run at public expense ', 11)
INSERT into test values (' A ', ' a ', ' Bus fee ', 9)
INSERT into test values (' A ', ' B ', ' phone fee ', 10)
INSERT into test values (' A ', ' B ', ' public expense ', 10)
INSERT into test values (' A ', ' C ', ' Bus fee ', 10)
INSERT into test values (' B ', ' d ', ' phone fee ', 10)
INSERT into test values (' B ', ' d ', ' public expense ', 11)
INSERT into test values (' B ', ' e ', ' bus fare ', 9)
INSERT into test values (' B ', ' f ', ' phone fee ', 10)
INSERT into test values (' B ', ' f ', ' public expense ', 10)
INSERT into test values (' B ', ' f ', ' bus fare ', 10)
SELECT * FROM Test
DECLARE @sql varchar (4000)
Set @sql = ' SELECT [Department],[customer] '
Select @sql = @sql + ', sum (isnull (case [fee name] when "+[fee name]+" then [amount] end,0)) as
[' +[fee name]+ '] '
From (select distinct [cost name] from [test]) as a
Select @sql = @sql + ' from [test] GROUP by [Department],[customer] '
EXEC (@sql)
Convert the value of a column field in a table to a column name in Microsoft SQL Server 2008