带动态列的sql pivot

时间:2017-04-11 10:38:19

标签: sql-server sql-server-2008

Expected Result will be like我已在链接sql group by order by and top in a same query中发布了我的问题,我的请求的结果是,

{{1}}

任何人都可以帮我转动此查询,提前谢谢

1 个答案:

答案 0 :(得分:0)

由于您的列表中有一定数量的雇员(来自您的评论),因此您不需要它是动态的。一个常规的枢轴应该可以做到这一点:

select [Company Name],Emp1,Emp2,Emp3,Emp4  from (
    SELECT
        [Company Name],
        [Employee Name],
        'Emp' + cast(ROW_NUMBER() OVER (PARTITION BY [Comp ID] ORDER BY  [Design ID], [Emp ID] desc) as char(2)) as RowNum
    FROM
    (
        SELECT emp.[Emp ID],
            comp.[Company Name],
            design.[Designation],
            emp.[Design ID],
            emp.[comp id],
            emp.[Employee Name],
            ROW_NUMBER() OVER (PARTITION BY emp.[Comp ID], emp.[Design ID] ORDER BY emp.[Comp ID] desc, emp.[Design ID] desc, emp.[Emp ID] desc) RowNum
        from employee as emp
            join designation as design on design.[Design ID]=emp.[Design ID]
            join company as comp on comp.[Comp ID]=emp.[Comp ID]
    ) a
    WHERE RowNum <=2
) as pivotdata
pivot (max([Employee Name]) for [RowNum] in (Emp1,Emp2,Emp3,Emp4)) as P