我有这样的数据
Col_A Col_B Col_C Value Col_E
Id_1 String_a type1 null Flat
Id_1 String_a type2 30 Not Flat
Id_1 String_b type1 null Flat
Id_1 String_b type2 30 Not Flat
Id_2 String_c type1 35 Flat
Id_2 String_c type2 55 Flat
我希望输出如下所示
Col_A type1_Col_E type1 type1_count type2_Col_E type_2 type2_count
Id_1 Flat null 0 Not Flat 30 2
Id_2 Flat 35 1 Flat 35 1
我需要将所有类型都作为列,并且需要将其每种类型都计为另一列。因此,如果我有2个与一个ID相关联的字符串,则其类型应为2。我需要将所有类型都作为列,并且需要计数以指示有多少个字符串与每种类型相关联。如果Value为空,则应将计数视为零。
是否可以使用PL SQL来实现?
答案 0 :(得分:0)
您不需要PL/SQL
,但是具有以下相关子查询的SQL Select
语句最适合您的情况,如下所示:
with tab( Col_A, Col_B, Col_C, Value, Col_E ) as
(
select 'Id_1','String_a','type1',null,'Flat' from dual union all
select 'Id_1','String_a','type2', 30,'Not Flat' from dual union all
select 'Id_1','String_b','type1',null,'Flat' from dual union all
select 'Id_1','String_b','type2', 30,'Not Flat' from dual union all
select 'Id_2','String_c','type1', 35,'Flat' from dual union all
select 'Id_2','String_c','type2', 55,'Flat' from dual
)
select Col_A,
( select distinct Col_E from tab where Col_A = t.Col_A and Col_C = 'type1' )
as type1_Col_E,
( select distinct value from tab where Col_A = t.Col_A and Col_C = 'type1' )
as type1,
( select sum(nvl2(value,1,0)) from tab where Col_A = t.Col_A and Col_C = 'type1' )
as type1_count,
( select distinct Col_E from tab where Col_A = t.Col_A and Col_C = 'type2' )
as type2_Col_E,
( select distinct value from tab where Col_A = t.Col_A and Col_C = 'type2' )
as type2,
( select sum(nvl2(value,1,0)) from tab where Col_A = t.Col_A and Col_C = 'type2' )
as type2_count
from tab t
group by t.Col_A;
COL_A TYPE1_COL_E TYPE1 TYPE1_COUNT TYPE2_COL_E TYPE2 TYPE2_COUNT
----- ----------- ------- ----------- ----------- ------ -----------
Id_1 Flat null 0 Not Flat 30 2
Id_2 Flat 35 1 Flat 35 1