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;
預期輸出:
-------- ----------- ----------- ---------- ----------
| E_ID | SRC_CNT | TGT_CNT | SRC_OTH | TGT_OTH |
-------- ----------- ----------- ---------- ----------
| 11 | 2 | 1 | 1 | 0 |
-------- ----------- ----------- ---------- ----------
目前,我正在對表中所有出現的 q_id 進行求和。說q_id13 它在表中出現 3 次,e_table對于所有q_id14、15 和 16 也是如此。但我想排除空值。如果a_value并且r_pos_a_id對于該特定 ID 為空,那么我必須從我的出現次數中排除該條目。例如,q_id13 是三次出現,但它應該只計算那些具有a_valueorr_pos_a_id和 exclude 具有a_valueandr_pos_a_id為 null 的那些。我必須為所有 q_id 做同樣的事情。
uj5u.com熱心網友回復:
將更多條件添加到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>
uj5u.com熱心網友回復:
但是,您可以DECODE通過與SIGNand連接來使用NVL2,這可以讓您替換空值和非空值,函陣列合,例如
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;
Demo
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422486.html
標籤:
上一篇:Psycopg2將sql資料庫連接到pandas資料框
下一篇:使用條件SQL從現有列創建新列
