2016-02-11 80 views
0

假設我有一個表下面的行和列SQL動態樞紐爲目標

EmpCode Empname Goals 
------- ----  ------ 
101  kiran  readsql 
101  kiran  coding 
101  kiran  readcss 
102  rohit  coding 
102  rohit  readjava 
103  pradi  do nothing 

我想在下面的格式來顯示上面的表格:

EmpCode Empname Goal1  Goal2 Goal3 
------- ----  ------  ------ ------ 
101  kiran  readsql coding readcss 
101  rohit  coding readjava 
103  pradi  do nothing 

的場均進球是動態的,請幫助我。謝謝。

+0

看一看的例子[這裏](https://technet.microsoft.com/en-us/library/ms177410(V = SQL.105)。 ASPX)。如果目標數量沒有最大限度,我想你可能會遇到問題。 –

+0

嗨骨頭,在上面的例子中,他使用了幾個星期來分組,但在我的情況下,提交的目標是varchar – kiransr

+0

它不會專門回答你的問題,但是直到別人在你身上發出響聲纔可能適應它,重新做,找到你自己的答案。它擊敗「刷新」等待。 :o) –

回答

0
CREATE TABLE #tt(id INT IDENTITY(1,1) PRIMARY KEY,EmpCode INT,Empname VARCHAR(2566),Goals VARCHAR(256)); 
INSERT INTO #tt(EmpCode,Empname,Goals)VALUES 
    (101,'kiran','readsql'), 
    (101,'kiran','coding'), 
    (101,'kiran','readcss'), 
    (102,'rohit','coding'), 
    (102,'rohit','readjava'), 
    (103,'pradi','do nothing'); 

DECLARE @goal_cols NVARCHAR(MAX)=STUFF((
    SELECT DISTINCT N',Goal'+CAST(ROW_NUMBER()OVER(PARTITION BY empcode ORDER BY id) AS VARCHAR(3)) 
    FROM #tt 
    FOR XML PATH('') 
    ),1,1,'' 
); 

DECLARE @stmt NVARCHAR(MAX)=N' 
    SELECT *  
    FROM (
      SELECT 
       EmpCode,Empname,Goals, 
       goal_id=''Goal''+CAST(ROW_NUMBER()OVER(PARTITION BY empcode ORDER BY id) AS VARCHAR(3)) 
      FROM 
       #tt 
     ) AS s 
     PIVOT(MAX(Goals) FOR goal_id IN ('[email protected]_cols+')) AS p 
    ORDER BY EmpCode;'; 

EXECUTE sp_executesql @stmt; 

DROP TABLE #tt; 

結果:

+---------+---------+------------+----------+---------+ 
| EmpCode | Empname | Goal1 | Goal2 | Goal3 | 
+---------+---------+------------+----------+---------+ 
|  101 | kiran | readsql | coding | readcss | 
|  102 | rohit | coding  | readjava | NULL | 
|  103 | pradi | do nothing | NULL  | NULL | 
+---------+---------+------------+----------+---------+ 
+0

真棒...謝謝TT :-) – kiransr