我有一张包含以下数据的表格
SQL> select * from mate2;
A_CD S_ID E_CD S_E S_NE E_IND
---------- ---------- ---------- ----- ----- -
100 1 3 A J Y
100 1 3 B A N
100 1 3 A D
200 2 3 A C Y
200 2 3 D C
300 3 3 B N Y
300 3 3 N N
我需要通过A_CD和(S_E,S_NE)将不同的S_E,S_NE组计为具有以下条件的字母代码:
当(E_CD = 3 AND E_IND = N)
当E_CD = 3且E_IND = Y
当E_CD = 3时,取S_NE的值并且E_IND为空并且DISPLAY E_IND为N
当E_CD = 3时,取S_E的值并且E_IND为空并且DISPLAY E_IND为Y
输出应如下所示。 L_C是S_E,S_NE
的计数A_CD L_C COUNT E_IND
---- --- ----- -----
100 A 3 Y
100 D 1 N
200 A 1 Y
200 D 1 Y
200 C 1 N
300 B 1 Y
300 N 1 Y
300 N 1 N
下面的样本表创建和数据用于测试
create table Mate2(a_cd number(5),S_ID NUMBER, E_CD number(10), S_E varchar2(5), S_NE varchar2(5), E_IND CHAR(1 byte));
insert into Mate2 values (100,1,3,'A','J','Y');
insert into Mate2 values (100,1,3,'B','A','N');
insert into Mate2(a_cd,S_ID,E_CD,S_E,S_NE) values (100,1,3,'A','D');
insert into Mate2 values (200,2,3,'A','C','Y');
insert into Mate2(a_cd,S_ID,E_CD,S_E,S_NE) values (200,2,3,'D','C');
insert into Mate2 values (300,3,3,'B','N','Y');
insert into Mate2(a_cd,S_ID,E_CD,S_E,S_NE) values (300,3,3,'N','N');
答案 0 :(得分:0)
您必须首先拆分E_IND
,然后才能简单
WITH data1 as (
SELECT A_CD, E_CD, S_E, S_NE,
CASE when E_CD = 3 and E_IND is null then 'N'
else E_IND
END as E_IND
FROM mate2
UNION ALL
SELECT A_CD, E_CD, S_E, S_NE, 'Y' E_IND
FROM mate2
WHERE E_CD = 3 and E_IND is null
)
SELECT A_CD, L_C, COUNT(*) as COUNT, E_IND FROM (
SELECT A_CD,
CASE when E_CD = 3 and E_IND = 'N' then S_NE
when E_CD = 3 and E_IND = 'Y' then S_E
else 'what_to_do_with_these'
END as L_C,
E_IND
FROM data1
)
GROUP BY A_CD, L_C, E_IND
order by A_CD, E_IND desc, L_C;
我在E_CD = 2
添加了一条额外的记录,以显示没有给出指令的情况。我想您的环境中存在此类数据,条件包括E_CD
insert into Mate2(a_cd,S_ID,E_CD,S_E,S_NE) values (100,1,2,'X','F');
输出
A_CD L_C COUNT E_IND
---- --- ----- -----
100 what_to_do_with_these 1 -
100 A 2 Y
100 A 1 N
100 D 1 N
200 A 1 Y
200 D 1 Y
200 C 1 N
300 B 1 Y
300 N 1 Y
300 N 1 N
遵循您的规则,给定的结果行100 A 3 Y
不正确,因为A
来自E_IND = N
答案 1 :(得分:-1)
不确定这是否是您要找的,似乎您的总记录数与您提供的所需输出不匹配,否则请尝试以下内容:
SELECT ABC.a_cd,ABC.L_C,COUNT(*)as COUNT,ABC.E_IND FROM (
select A_CD, case when E_CD = 3 and E_IND = 'N' then S_NE
when E_CD = 3 and E_IND = 'Y' then S_E
when E_CD = 3 and E_IND is null then S_NE
when E_CD = 3 and E_IND is null then S_E
end as L_C,
case when E_CD = 3 and E_IND is null then 'N'
when E_CD = 3 and E_IND is not null then 'Y'
else E_IND
end as E_IND
FROM Mate2) as ABC
GROUP BY ABC.a_cd, ABC.L_C,ABC.E_IND