2014-08-30 118 views
0

我需要改造如下的數據:樞軸/逆透視表

EmployeeId  DataCategory  DataValue  StartDate 
----------  ------------  ---------- ---------- 
    2   'OfficeCode'   121  '03-01-12' 
    2   'ManagerName'  'Steven'  '02-04-12' 
    2   'State'    'MA'  '04-05-12' 
    5   'OfficeCode'   133  '04-01-12' 
    5   'ManagerName'  'Marcus'  '05-04-12' 
    5   'State'    'WA'  '01-05-12' 
    6   'ManagerName'  'Steven'  '07-04-12' 
    6   'State'    'RI'  '06-05-12' 
    7   'State'    'CA'  '08-08-12' 

到:

EmployeeId  OfficeCode  ManagerName State  OfficeCodeStartDate 
----------  ------------  ---------- ---------- ------------------- 
    2    121   'Steven'  'MA'   '03-01-12' 
    5    133   'Marcus'  'WA'   '04-01-12' 
    6    null   'Steven'  'RI'   null 
    7    null   null   'CA'   null 

我能夠樞轉這樣的:

select EmployeeId, OfficeCode, ManagerName, State 
from 
(
    select EmployeeId, DataCategory, DataValue 
    from emp 
) src 
pivot 
(
    max(DataValue) 
    for DataCategory in (OfficeCode, ManagerName, State) 
) piv 

然而,我還需要DataCategory OfficeCode的StartDate(忽略任何其他類別的開始日期)。你能幫我用pivot/unpivot實現想要的結果嗎?除非需要,我試圖避免聯合/聯合。

回答

1

三種方式:一種是UNION,一種是JOIN,一種是沒有PIVOT。選擇一個你最喜歡的(根據查詢計劃,最後一個是最快的)。

/* 
CREATE TABLE emp (
    EmployeeId INT, 
    DataCategory VARCHAR(50), 
    PRIMARY KEY (EmployeeID, DataCategory), 
    DataValue VARCHAR(50) NOT NULL, 
    StartDate VARCHAR(10) NOT NULL 
) 

INSERT INTO emp VALUES 
('2','OfficeCode','121','03-01-12'), 
('2','ManagerName','Steven','02-04-12'), 
('2','State','MA','04-05-12'), 
('5','OfficeCode','133','04-01-12'), 
('5','ManagerName','Marcus','05-04-12'), 
('5','State','WA','01-05-12'), 
('6','ManagerName','Steven','07-04-12'), 
('6','State','RI','06-05-12'), 
('7','State','CA','08-08-12') 
*/ 

select EmployeeId, OfficeCode, ManagerName, State, OfficeCodeStartDate 
from 
(
    select EmployeeId, DataCategory, DataValue 
    from emp 
    union all 
    select EmployeeId, 'OfficeCodeStartDate' AS DataCategory, StartDate AS DataValue 
    from emp 
    WHERE DataCategory='OfficeCode' 
) src 
pivot 
(
    max(DataValue) 
    for DataCategory in (OfficeCode, ManagerName, State, OfficeCodeStartDate) 
) piv 

select piv.EmployeeId, OfficeCode, ManagerName, State, emp.StartDate AS OfficeCodeStartDate 
from 
(
    select EmployeeId, DataCategory, DataValue 
    from emp 
) src 
pivot 
(
    max(DataValue) 
    for DataCategory in (OfficeCode, ManagerName, State) 
) piv 
LEFT JOIN emp ON emp.EmployeeId=piv.EmployeeId AND emp.DataCategory='OfficeCode' 

SELECT EmployeeId, 
    MIN(CASE WHEN DataCategory='OfficeCode' THEN DataValue END) AS OfficeCode, 
    MIN(CASE WHEN DataCategory='ManagerName' THEN DataValue END) AS ManagerName, 
    MIN(CASE WHEN DataCategory='State' THEN DataValue END) AS State, 
    MIN(CASE WHEN DataCategory='OfficeCode' THEN StartDate END) AS OfficeCodeStartDate 
FROM emp 
GROUP BY EmployeeId