我在表格中有一些数据要使用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;
我希望数据显示如下..
我很难搞清楚。请告诉我。
答案 0 :(得分:2)
这里是没有PIVOT和UNPIVOT的SELECT语句。如你所见,它更复杂:
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
答案 1 :(得分: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;