SQL如果“某事”选择计数

时间:2010-02-03 21:44:41

标签: sql tsql select count sum

来自我的自定义视图的输出如下......

Col1    Col2    Col3   Col4

xxxx    Cake    1      1*
Cake    xxxx    2*     1
xxxx    Cake    2      0*
xxxx    Cake    0      0*
Cake    xxxx    2*     0
Cake    xxxx    2*     0

我想要总结的是......

For every row, 
if the word Cake is found in Col1, then add the value of Col3 to Sum
else add the value of Col4 to sum

从上面的视图得到的SUM应该是1 + 2 + 0 + 0 + 2 + 2 = 7

提前致谢!

P.S。添加星号只是为了显示,应将这些数字添加到总和中。

5 个答案:

答案 0 :(得分:12)

的内容
select
   SUM( 
     Case 
         when Col1 = 'Cake' then Col3 
         when Col2 = 'Cake' then Col4 
         else 0 END 
   ) as MySum
from TheView

答案 1 :(得分:1)

在MySQL中,你可以做到

SELECT SUM(IF(Col1 LIKE 'cake', Col3, Col4)) AS MySum

我不确定其他变体的语法。顺便提一下,已经提供的答案

SELECT
   SUM( 
     CASE 
         WHEN Col1 = 'Cake' THEN Col3 
         WHEN Col2 = 'Cake' THEN Col4 
         ELSE 0 END 
   ) AS MySum

没有给出正确的结果 - 根据规范,当Col1中没有出现'cake'时,应该添加Col4,而不仅仅是它出现在Col2中。

答案 2 :(得分:1)

因此,基于Franks和Duncan的答案,以下应该是您所需要的......

select SUM( Case 
                when Col1 = 'Cake' then Col3 
                else Col4 END ) as MySum
from TheView

答案 3 :(得分:0)

create table #sample
(
    Col1 varchar(50),
    Col2 varchar(50),
    Col3 int,
    Col4 int
)

insert into #sample VALUES ('xxxx', 'Cake', 1, 1);
insert into #sample VALUES ('Cake', 'xxxx', 2, 1);
insert into #sample VALUES ('xxxx', 'Cake', 2, 0);
insert into #sample VALUES ('xxxx', 'Cake', 0, 0);
insert into #sample VALUES ('Cake', 'xxxx', 2, 0);
insert into #sample VALUES ('Cake', 'xxxx', 2, 0);


select sum(case
           when Col1 = 'Cake' then Col3
           when Col2 = 'Cake' then Col4
           else 0
       end) as [value]
from  #sample

答案 4 :(得分:0)

在Oracle中,Craig的答案可行,或者您可以使用如下解码:

SELECT SUM(DECODE(Col1,'Cake',Col3,Col4)) FROM TheView;