简体   繁体   English

MySQL SELECT IF区分SUM

[英]MySQL SELECT IF differentiate SUM

My database structure looks as follows: 我的数据库结构如下所示:

id    |    valuefor   |    quantity
1          alpha           500
2          alpha           100
3          beta            200

I am using following mysql command 我正在使用以下mysql命令

SELECT IF(valuefor=alpha, SUM(quantity),0) as alpha
     , IF(valuefor=beta, SUM(quantity),0) as beta 
  FROM mytable

Current Output: 电流输出:

alpha   |   beta
800         0

The obvious issue with the above is that it SUMS all the rows since I have used SUM. 上面的明显问题是自从我使用SUM以来,它汇总了所有行。 How can I overcome this dilemma? 我如何克服这个难题? I want to get quantity of alpha and beta separately. 我想分别获取alpha和beta的数量。

Secondly I am confused as to why did the beta not have value=800 in the output and why does it say 0. This is just for my better understanding of the issue. 其次,我对为什么beta在输出中没有value = 800以及为什么它说0感到困惑。这只是出于我对问题的更好理解。

I want to result to look something as follows: 我想得出的结果如下所示:

alpha    |    beta
600           200

Try this: 尝试这个:

SELECT SUM(CASE WHEN valuefor=alpha THEN quantity ELSE 0 END) AS alpha,
       SUM(CASE WHEN valuefor=beta THEN quantity ELSE 0 END) AS beta
FROM mytable

You can use the case statement for that like so: 您可以这样使用case语句:

select
  sum(case valuefor when 'alpha' then quantity else 0 end) as alpha,
  sum(case valuefor when 'beta' then quantity else 0 end) as beta
from test;

Example: 例:

http://sqlfiddle.com/#!9/f07bbf http://sqlfiddle.com/#!9/f07bbf

create table test (
  id int,
  valuefor varchar(20),
  quantity int
);

insert into test values
(1, 'alpha', 500),
(2, 'alpha', 100),
(3, 'beta', 200);

Result 结果

| alpha | beta |
|-------|------|
|   600 |  200 |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM