在sqlserver 2008中将行交换为列

时间:2015-10-08 07:24:59

标签: sql sql-server sql-server-2008

如何将行与列互换, 我有像

这样的输出
 employeeName   payHead  amount

Samam          Basic    20000.000000 
Samam          Test1    11.000000
Samam          Test2    22.000000   
Ravi kumar     Test1    55.000000
Ravi kumar     Test2    66.000000
Ravi kumar     Basic    3000.000000

我需要像

这样的输出
employeeName   Basic             Test1         Test2   

 Samam          20000.000000      11.000000    22.000000 
 Ravi kumar     3000.000000       55.000000    66.000000

1 个答案:

答案 0 :(得分:2)

简单PIVOT查询:

DECLARE @Test TABLE (employeeName  nvarchar(max),
                     payHead nvarchar(max),
                     amount float);

INSERT INTO @Test
VALUES
('Samam',          'Basic',    20000.000000),
('Samam',          'Test1',    11.000000),
('Samam',          'Test2',    22.000000),   
('Ravi kumar',     'Test1',    55.000000),
('Ravi kumar',     'Test2',    66.000000),
('Ravi kumar',     'Basic',    3000.000000);

SELECT *
FROM @Test t
PIVOT
(
    MAX(amount)
    FOR payHead IN (Basic,Test1,Test2)
) as p
ORDER BY Basic;