如何選擇一個變量,它給出了一個輸出一樣的Excel函數:如何在Oracle
COUNTIFS(A1:D1,"<25", A1:D1, ">16")?
即算在我的四個領域的時間值數爲您會使用case
做16和25之間
如何選擇一個變量,它給出了一個輸出一樣的Excel函數:如何在Oracle
COUNTIFS(A1:D1,"<25", A1:D1, ">16")?
即算在我的四個領域的時間值數爲您會使用case
做16和25之間
您可以count()
和case
表達式做到這一點。注:case
有一個可選的else
子句;如果未使用,則默認else
「值」爲null
。計數只計數非空值,所以你可以結合這些觀察來編寫緊湊的代碼。計算什麼並不重要;所以case
表達式可能會返回一個數字(1是通常的,但0是一樣有效的,並且會給出相同的結果,因爲值是COUNTED,而不是SUMMED) - 但是您也可以有一個字符串,如'x'或日期在表達式的情況下。爲了說明這一點,我將使用一個字符串。
select count(case when col > 16 and col < 25 then 'x' end) as ct from your_table;
這裏your_table
是您的表的名稱,col
是包含值的柱的名稱,並ct
是結果列的名稱(滿足你的條件值的計數的標籤)。
當然,在一個數據庫中,你可以更容易地獲得相同的結果:
select count(*) as ct from your_table where col > 16 and col < 25;
但是請注意,這些值是在一列。
如果您有一個包含四個COLUMNS和許多行的表,並且所有列中的所有值都是數字,並且您希望添加一列顯示在每行中嚴格介於16和25之間的值,那麼解決方案是不同的(但它使用同樣的想法):
select col1, col2, col3, col4,
case when col1 > 16 and col1 < 25 then 1 else 0 end +
case when col2 > 16 and col2 < 25 then 1 else 0 end +
case when col3 > 16 and col3 < 25 then 1 else 0 end +
case when col4 > 16 and col4 < 25 then 1 else 0 end as ct
from my_table;
這在一個SQL查詢:
select sum(case when col between 16 and 25 then 1 else 0 end)
from t;
注意between
是包容性的SQL,不敢獨享,那麼根據您的代碼邏輯:
select sum(case when col > 16 and col < 25 then 1 else 0 end)
from t;
想,你有一個'user_table'
,其中一些用戶的「狀態」是active (code-11)
和其他人inactive (code-22)
。您可以使用下面的這個sql
來計數有效和無效。
select count(case when status = 11 then 1 end) u_active, count(case when status = 22 then 1 end) u_inactive, from user_table;