sql >> Database teknologi >  >> RDS >> Sqlserver

sql pivot med dynamiske kolonner

Da du har et fast antal ansatte på din liste (fra din kommentar), behøver du ikke, at den er dynamisk. En almindelig pivot burde gøre det trick:

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



  1. Angiv kolonner for PDO::FETCH_KEY_PAIR

  2. Sådan installeres MySQL 5.7 på Amazon ec2

  3. SQL-afhængighed af en MariaDB/MySQL-database

  4. Sorter 0-værdi database rækker efter ikke-nul rækker