2014-10-28 76 views
0

我在表中使用SQL轉置一些數據。這裏是示例數據。使用Oracle SQL轉置表格

create table test_pivot(
Name varchar2(100), 
DeptA varchar2(50), 
DeptB varchar2(50), 
DeptC varchar2(50), 
DeptD varchar2(50) 
); 

insert all 
into test_pivot(Name,DeptA,DeptB,DeptC,DeptD) 
values('Asfakul','Y',NULL,NULL,NULL) 
into test_pivot(Name,DeptA,DeptB,DeptC,DeptD) 
values('Debmalya',NULL,'Y',NULL,NULL) 
into test_pivot(Name,DeptA,DeptB,DeptC,DeptD) 
values('Ranjan',NULL,NULL,'Y',NULL) 
into test_pivot(Name,DeptA,DeptB,DeptC,DeptD) 
values('santanu',NULL,NULL,NULL,'Y') 
select 1 from dual; 

我要顯示像下面的數據..

enter image description here

我有一個艱難的時間計算出來。請告訴我。

+2

你知道你想旋轉,所以你用pivot操作符有多遠?或者你還在一個不支持它的舊版本上? – 2014-10-28 11:20:55

+0

我認爲這是UNPIVOT操作。我仍在嘗試。 – redsoxlost 2014-10-28 11:22:56

回答

1

如果您的數據庫版本支持pivot和unpivot,那麼您可以使用相同的。 請參見下面的查詢,我想這應該幫助你..

SELECT * 
    FROM( SELECT * 
      FROM test_pivot 
     UNPIVOT (Check_val FOR DEPT IN (DEPTA, DEPTB, DEPTC, DEPTD)) 
    ) 
PIVOT(MAX(check_val) FOR NAME IN ('Asfakul' AS Asfakul, 
            'Debmalya' AS Debmalya, 
            'Ranjan' AS Ranjan, 
            'santanu' AS santanu)) 
ORDER BY dept; 

+0

謝謝。但是我們可以使用sql Only嗎? – redsoxlost 2014-10-28 11:58:25

+0

當然可以...但性能明智的使用樞軸是有用的.. – 2014-10-28 12:00:48

+0

我們如何才能實現使用相同的SQL ..你能指導 – redsoxlost 2014-10-28 12:10:53

2

這裏的SELECT語句不PIVOT和UNPIVOT。正如你所看到的,它要複雜得多:

select dept, 
     nvl(max(case when name = 'Asfakul' then dept_val end), 'N') as Asfakul, 
     nvl(max(case when name = 'Debmalya' then dept_val end), 'N') as Debmalya, 
     nvl(max(case when name = 'Ranjan' then dept_val end), 'N') as Ranjan, 
     nvl(max(case when name = 'santanu' then dept_val end), 'N') as santanu 
    from(select name, 
       dept, 
       case when dept = 'depta' then depta 
        when dept = 'deptb' then deptb 
        when dept = 'deptc' then deptc 
        when dept = 'deptd' then deptd 
       end dept_val 
     from test_pivot 
     join(select 'depta' as dept from dual union all 
       select 'deptb' as dept from dual union all 
       select 'deptc' as dept from dual union all 
       select 'deptd' as dept from dual 
      ) 
      on 1 = 1 
    ) 
group 
    by dept 
order 
    by dept