2015-10-19 44 views
1

我知道很多關於SQL表格格式化的問題,但我找不到解決當前問題的方法。將行轉換爲SQL中的列的自定義處理

我的問題是,我有一個表包含有關公司的數據以及與這些公司有關的員工。

Company_ID Person_ID Name      Departement_ID 
1   1   aaa        1   
1   2   bbb        1   
1   3   ccc        1   
1   4   ddd        2   
2   5   eee        1   
2   6   fff        2   
2   7   ggg        2   

我想顯示每個公司每個部門2個員工數據的樣本。第一部分的結果會是這樣的:

Company_ID Contact1ID_Dpt1 Contact1Name_Dpt1 Contact2ID_Dpt1 Contact2Name_Dpt1 
1   1    aaa    2    bbb 
2   5    eee    NULL   NULL 

有人可以幫我解決這個問題嗎?

回答

0

類似戈登的例子,但你不是真的需要包括你的group by或您的ROW_NUMBER()..百貨,如果你想添加一個DEPARTEMENT過濾器,你會在你的子查詢中添加它..

DECLARE @Table1 TABLE (
    Company_ID INT, 
    Person_ID INT, 
    [Name] VARCHAR(MAX), 
    Departement_ID INT 
    ) 
INSERT INTO @Table1 
VALUES 
     (1,1,'aaa',1), 
     (1,2,'bbb',1), 
     (1,3,'ccc',1), 
     (1,4,'ddd',2), 
     (2,5,'eee',1), 
     (2,6,'fff',2), 
     (2,7,'ggg',2) 

DECLARE @Departement INT = 1 
SELECT 
    Company_ID, 
    MAX(CASE WHEN seqnum = 1 THEN Person_ID END) AS Contact1ID_Dpt, 
    MAX(CASE WHEN seqnum = 1 THEN [Name] END) AS Contact1Name_Dpt, 
    MAX(CASE WHEN seqnum = 2 THEN Person_ID END) AS Contact2ID_Dpt, 
    MAX(CASE WHEN seqnum = 2 THEN [Name] END) AS Contact2Name_Dpt 
FROM 
    (SELECT 
     t.*, 
     ROW_NUMBER() OVER (PARTITION BY Company_ID ORDER BY Person_ID) AS seqnum 
    FROM 
     @Table1 t 
    WHERE --add your department filter here. 
     Departement_ID = @Departement 
    ) t 

GROUP BY 
    Company_ID; 
1

這是一個可以使用row_number()和條件聚合輕鬆完成的示例。

select company_id, department_id, 
     max(case when seqnum = 1 then name end) as name1, 
     max(case when seqnum = 2 then name end) as name1. 
from (select t.*, 
      row_number() over (company_id, department_id order by newid()) as seqnum 
     from t 
    ) t 
group by company_id, department_id; 

如果您願意,您可以添加一個篩選器以僅獲取一個部門。