TSQL PIVOT COLUMNS的一部分

时间:2014-02-04 02:08:40

标签: sql sql-server tsql pivot

我有下表但不确定是否可以从表中转动某些列:

CREATE TABLE #test ( id int, Area varchar(10), [grouping] varchar(15), task_1 int, task_2 int)

INSERT INTO #test Values (10,'A','HighNeeds',1, 10)
INSERT INTO #test Values (10,'B','HighNeeds',1, 12)
INSERT INTO #test Values (12,'C','Non HighNeeds',2, 14)

select * from #test
-------------------------------------------------
id  Area    grouping        task_1  task_2
10  A       HighNeeds       1       10
10  B       HighNeeds       1       12
12  C       Non HighNeeds   2       14

What I'm trying to get is:
-------------------------------------------------
id  Area    Tasks      HighNeeds   Non HighNeeds   
10  A       task_1     1           NULL
10  A       task_2     10          NULL
10  B       task_1     1           NULL
10  B       task_2     12          NULL
12  C       task_1     NULL        2
12  C       takk_2     NULL        14

基本上我正在尝试保留IDArea列,但是转移分组数据和任务列。

1 个答案:

答案 0 :(得分:0)

这非常棘手 - 您需要将Grouping作为列进行转换,并将task_1task_2作为行值取消:

SELECT *
FROM
(
    SELECT 
        id, Area, grouping, tskCount, Task
    FROM 
        test
    UNPIVOT 
    (
       tskCount
       for Task in (task_1, task_2)
    ) unpvt
) X
PIVOT
(
 SUM(tskCount)
 for grouping in (HighNeeds, [Non HighNeeds])
)pvt;

Fiddle here