如何在列侧获取行数据

时间:2012-10-19 18:56:25

标签: sql-server sql-server-2008

我有一张员工表,工资按年数计算如下:

Employee_table
-----------------------------------------------------------------------------
emp_ID -  FirstName- LstName   salary  ...    year -  
001   -   xx     -     yy   -   03212         2000       
001   -   xx     -     yy   -   04212         2001        
002   -   xxx     -    yyy  -   03425         2000         
002   -   xxx     -    yyy  -   04425         2001          
003   -   xxxx    -    yyyy  -  03429         2000         
003   -   xxxx   -     yyyy  -  04429         2001         
------------------------------------------------------------------------------

我想写一个查询,它会在列方面给我一年的员工数据:

tblResults
---------------------------------------------------------------------
emp_ID   2000       2001          ....     ....            
---------------------------------------------------------------------
01        03212     04212   
02        03425   - 04425    
03        03429     04429   

1 个答案:

答案 0 :(得分:5)

好的,正如@SpectralGhost所说,你可以使用PIVOT。如果您事先知道需要多少年,那么您可以这样做:

SELECT *
FROM (  SELECT emp_ID, salary, [year]
        FROM Employee_Table) AS ET
PIVOT(MIN(salary) FOR [year] IN ([2000],[2001],[2002])) AS PT

如果您不知道有多少年,那么您将需要动态SQL(首先,转到this link)。然后试试这个:

DECLARE @Years NVARCHAR(MAX), @Query NVARCHAR(MAX)

SELECT @Years = STUFF(( SELECT DISTINCT ',' + QUOTENAME([year]) 
                        FROM Employee_Table
                        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')

SET @Query = '
SELECT *
FROM (  SELECT emp_ID, salary, [year]
        FROM Employee_Table) AS ET
PIVOT(MIN(salary) FOR [year] IN ('+@Years+')) AS PT'

EXEC(@Query)