2011-06-07 58 views
2

我在SQL Server 2008中的如下表:SQL查詢行轉換成列

[ID] [Filiale] [Mitarbeiter] 
1 01  Müller 
2 01  Meier 
3 01  Schmidt 
4 02  Schulz 
5 02  Schröder 

我需要它創建以下輸出的查詢:

[Filiale] [Mitarbeiter1] [Mitarbeiter2] [Mitarbeiter3] [Mitarbeiter4] [Mitarbeiter5] 
01  Müller   Meier   Schmidt  NULL   NULL 
02  Schulz   Schröder  NULL   NULL   NULL 

列可以固定到[Mitarbeiter1] - [Mitarbeiter5],因爲每個Filiale的行數不會超過5行。

非常感謝您的幫助!

+0

重複:http://stackoverflow.com/questions/1768586/sql-convert-rows-to-columns – manji 2011-06-07 15:31:57

+0

我張貼我的問題之前,檢查了這一點,但沒能解決適應解決我的問題。 – 2011-06-07 15:53:07

回答

2

使用SQL Server 2008的數據透視和排名功能結合爲每個員工數量提供了期望的結果 首先我們爲每個分支中的每個分支分配一個ID,每個分支中以1開頭,然後我們使用數據透視運算符翻轉結果

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

完美!這正是我所期待的。謝謝! – 2011-06-07 18:55:13