[英]How to exclude null values when using DECODE in SELECT query
CREATE TABLE e_table
(
e_id NUMBER(10),
q_id NUMBER(10),
a_value VARCHAR2(20),
r_pos_a_id NUMBER(10)
);
INSERT INTO e_table VALUES( 11, 13, null , null );
INSERT INTO e_table VALUES( 11, 15, null , null );
INSERT INTO e_table VALUES( 11, 14, null , null );
INSERT INTO e_table VALUES( 11, 16, null , null );
INSERT INTO e_table VALUES( 11, 13, null , 992 );
INSERT INTO e_table VALUES( 11, 13, null , 637 );
INSERT INTO e_table VALUES( 11, 15, null , 637 );
INSERT INTO e_table VALUES( 11, 14,'Manual', null );
SELECT e_id,
SUM(decode(q_id, 13, 1, 0)) src_cnt,
SUM(decode(q_id, 15, 1, 0)) tgt_cnt,
SUM(decode(q_id, 14, 1, 0)) src_oth,
SUM(decode(q_id, 16, 1, 0)) tgt_oth
FROM e_table
GROUP BY e_id;
预期 output:
+--------+-----------+-----------+----------+----------+
| E_ID | SRC_CNT | TGT_CNT | SRC_OTH | TGT_OTH |
+--------+-----------+-----------+----------+----------+
| 11 | 2 | 1 | 1 | 0 |
+--------+-----------+-----------+----------+----------+
目前,我正在对表中所有出现的 q_id 进行求和。 说q_id
13 它在表e_table
中出现 3 次,对于所有q_id
即 14、15 和 16 也是如此。但我想排除 null 值。 如果该特定 id 的a_value
和r_pos_a_id
是 null ,那么我必须从我的出现次数中排除该条目。 例如, q_id
13 是三次出现的,但它应该只计算具有a_value
或r_pos_a_id
的那些,并且排除同时具有a_value
和r_pos_a_id
作为 null 的那些。 我必须为所有 q_id 做同样的事情。
在CASE
中添加更多条件。 为什么是CASE
而不是DECODE
? 因为它允许灵活性。
SQL> select e_id,
2 sum(case when q_id = 13 and (a_value is not null or r_pos_a_id is not null) then 1 else 0 end) src_cnt,
3 sum(case when q_id = 15 and (a_value is not null or r_pos_a_id is not null) then 1 else 0 end) tgt_cnt,
4 sum(case when q_id = 14 and (a_value is not null or r_pos_a_id is not null) then 1 else 0 end) src_oth,
5 sum(case when q_id = 16 and (a_value is not null or r_pos_a_id is not null) then 1 else 0 end) tgt_oth
6 from e_table
7 group by e_id;
E_ID SRC_CNT TGT_CNT SRC_OTH TGT_OTH
---------- ---------- ---------- ---------- ----------
11 2 1 1 0
SQL>
但是您可以通过与SIGN
和NVL2
连接来使用DECODE
,这可以让您替换 null 和非空值,功能组合,例如
SELECT e_id,
SUM(DECODE(q_id, 13, SIGN(NVL2(a_value,1,0))+SIGN(NVL2(r_pos_a_id,1,0)))) AS src_cnt,
SUM(DECODE(q_id, 15, SIGN(NVL2(a_value,1,0))+SIGN(NVL2(r_pos_a_id,1,0)))) AS tgt_cnt,
SUM(DECODE(q_id, 14, SIGN(NVL2(a_value,1,0))+SIGN(NVL2(r_pos_a_id,1,0)))) AS src_oth,
SUM(DECODE(q_id, 16, SIGN(NVL2(a_value,1,0))+SIGN(NVL2(r_pos_a_id,1,0)))) AS tgt_oth
FROM e_table
GROUP BY e_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.