SQL query to convert rows into columns

前端 未结 1 1486
广开言路
广开言路 2021-01-21 22:02

I have the following table in SQL Server 2008:

[ID] [Filiale] [Mitarbeiter]
1    01        Müller
2    01        Meier
3    01        Schmidt
4    02        Schu         


        
相关标签:
1条回答
  • 2021-01-21 22:19

    With SQL Server 2008 the Pivot and Ranking functions combined give you the desired result for each number of employees First we assign an ID to each empoyee in each branch starting with 1 in each new branch then we use the pivot operator to flip the result

    create table data
    (
    id int, 
    branch int, 
    employee varchar(20)
    )
    
     insert into data (id, branch, employee) values
     (1, 1, 'Müller'),
     (2, 1, 'Meler'),
     (3, 1, 'Schmidt'),
     (4, 1, 'Schultz'),
     (5, 2, 'Schröder'),
     (6, 2, '=tg= Thomas'),
     (7, 3, 'Stephan')
    
    
    select branch, [1] as emp1, [2] as emp2, [3] as emp3, [4] as emp4, [5] emp5 
    from
    (
      select ROW_NUMBER() over (partition by branch order by id) employee_branch_id, branch, employee 
        from data
    ) data_with_employee_branch_id -- assign a number from 1 to n for each emplyee in the branch 
    pivot 
    (
      max(employee) --it must be a aggregat, since we have only one row the max of a string will be the string
      for employee_branch_id in ( [1], [2], [3], [4], [5] )
    ) as data_pvt
    
    0 讨论(0)
提交回复
热议问题