![](/img/trans.png)
[英]Query to update 1 column with no condition and another column only if certain condition is met
[英]Count only if condition on another column met
只有滿足其他列條件時,我才需要計算ID。 ID不是唯一的,可能包括幾個步驟。
表看起來像:
rownum | ID | key | result
1 |100 | step1 | accepted
2 |100 | step2 | accepted
3 |100 | step3 | transfer
4 |101 | step0 | accepted
5 |101 | step1 | accepted
6 |101 | step2 | rejected
7 |102 | step0 | accepted
8 |102 | step1 | accepted
9 |103 | step1 | rejected
10 |104 | step1 | rejected
11 |104 | step1 | rejected
12 |104 | step1 | rejected
在示例中,我有5個ID(但在實際表中有數千個ID),我必須僅COUNT條符合條件的ID。 條件很簡單:鍵<>'step0',因此我的COUNT腳本應返回值3。
如果我試試
COUNT ID
FROM myTable
WHERE key <> 'step0'
它返回錯誤的值,因為WHERE子句在COUNT之前應用
任何想法都贊賞。
這是一個不需要嵌套聚合函數且不需要子查詢的方法:
select (count(distinct id) -
count(distinct case when key = 'step0' then id end)
)
from mytable;
嘗試使用不存在的相關子查詢
select count(distinct ID)
from tablename a
where not exists (select 1 from tablename b where a.id=b.id and key = 'step0')
使用不同
select COUNT (distinct ID)
FROM myTable
WHERE ID not in ( select id from myTable where key = 'step0' and id is not null)
使用帶有having子句的分組
select sum(count(distinct ID)) as "Count"
from myTable
group by ID
having sum(case when key = 'step0' then 1 else 0 end)=0;
-- or "having sum( decode(key,'step0',1,0) ) = 0" is also possible specific to Oracle
Count
-----
3
例如使用反向邏輯,來自key = 'step0'
這應該工作:
SELECT COUNT(COUNT(DISTINCT id)) num_ids
FROM your_table
GROUP BY id
HAVING MIN(CASE WHEN key = 'step0' THEN key END) IS NULL;
外部COUNT
適用於整個查詢,包括COUNT(DISTINCT id)
的聚合 - 刪除它,您將看到三行值為1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.