总结一下-Oracle

时间:2016-04-13 18:58:55

标签: sql 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

2 个答案:

答案 0 :(得分:1)

您可以使用以下方式计算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
...

答案 1 :(得分:1)

如果您只对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;