簡體   English   中英

以防萬一-Oracle

[英]Sum in case -Oracle

我有以下查詢:

select Type,

sum (case when a=1 then 1 end) as A,

sum (case when a=0 then 1 end) as B

這將顯示2列A,B及其總數。 我需要的是第三列,該列將顯示每行A和B的總和。 就像是:

Type       A         B      Total

Apple      5                  5

Orange     3         4        7

Kiwi       2         1        3

Peach                6        6

我已經嘗試了以下方法,但似乎不起作用:

select Type,

sum (case when a=1 then 1 end) as A,

sum (case when a=0 then 1 end) as B,

sum (A+B) as Total

您可以使用以下方法計算Total

select Type,
  sum(case when a=1 then 1 end)        as A,
  sum(case when a=0 then 1 end)        as B,
  sum(case when a IN (0,1) then 1 end) as Total
...

如果您只對0和1值感興趣,那么這可能會更簡單:

select Type, sum(a) as A, sum(1 - a) as B, count(*) as Total
from t
where a in (0, 1)
group by Type;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM