带有pivot操作符的动态表

时间:2014-09-04 05:39:34

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

我的表

cname |  ename 
------+-------      
aaa   |   aaaa      
raj   |   tesfsa    
raj   |   aaaa  

需要看起来像这样

cname   |   interviewer1   |   interviewer2  
--------+------------------+------------------- 
raj     |       aaaa       |       tesfsa   
aaa     |       aaaa       |

cname可以有多个面试官(动态)......这就是问题..

我认为需要使用动态枢轴操作员,我对枢轴有很多了解...请帮帮我们......

1 个答案:

答案 0 :(得分:2)

SQL FIDDLE

这正是你想要的。

create procedure pro
as
BEGIN

DECLARE @colsName VARCHAR(MAX);
DECLARE @cols VARCHAR(MAX);
DECLARE @query NVARCHAR(MAX);

CREATE TABLE #temp
( 
     cname VARCHAR(50),
     ename VARCHAR(50)
)

INSERT INTO #temp
select (c.Firstname+c.Lastname) as cname,(e.EmployeeFName+e.EmployeeLName) as ename  
from CandidateProfile c inner join JobApplied ja on (ja.ProfileId = c.ProfileID)
inner join JobInterview ji on (ja.JobApplyUID = ji.JobApplyUID) 
inner join Employees e on (ji.InterviewBy = e.EmployeeID) 
group by c.Firstname+c.Lastname,InterviewTimeFrom,e.EmployeeFName+e.EmployeeLName




SELECT @colsName = COALESCE(@colsName + ', ','') + colName 
FROM   (select distinct ename + ' AS interviewer' +
convert(varchar, DENSE_RANK() OVER (ORDER BY ename ASC)) as colName
FROM #temp) a


SELECT @cols = COALESCE(@cols + ', ','') + ename 
FROM   (select distinct ename
FROM #temp) b


SET @query = N'SELECT cname, '+
@colsname +'
FROM #temp
PIVOT
(
MAX(ename)
FOR ename IN
( '+@cols +' )
) AS pvt'


EXECUTE(@query)

DROP TABLE #temp

END