SQL SUM值满足2个条件

时间:2014-01-03 13:58:14

标签: mysql sql sql-server select

我正在尝试创建一个计算每个月的信用卡和借记卡的查询。这些值在名为SUM的列中,每个记录都有一个字段,表示它是信用卡还是借记卡(ex_type)。我已经设法得到所有字段的总和(虽然它也不正确 - 但我只是将所有值相加,无论是信用还是借记)。

SELECT sum(sum) as total FROM acc where month='$month'

但我无法想办理信用卡和借记卡

所以,总结一下......我希望将以下两个查询合二为一。

1. Select sum(sum) as Debit from acc where ex_type='Debit' and month='$month'
2. Select sum(sum) as Credit from acc where ex_type='Credit' and month='$month'

所以,非常感谢任何帮助。

6 个答案:

答案 0 :(得分:6)

使用CASE

尝试此操作
Select sum(CASE WHEN ex_type='Debit' THEN `sum` ELSE 0 END) as Debit,
sum(CASE WHEN ex_type='Credit' THEN `sum` ELSE 0 END) as Credit FROM ...

答案 1 :(得分:1)

这应该有效:

Select sum(d.sum) as Debit, 
  (Select sum(c.sum) from acc c where c.ex_type='Credit' and c.month='$month') as Credit
from acc d where d.ex_type='Debit' and d.month='$month'

但是,如果您在其他字段中提供更多详细信息,则可以将内部联接到同一个表中,这可能会稍微提高效率。

答案 2 :(得分:1)

也许重复帖子:

SUM() based on a different condition to the SELECT

试试这个:

Select 
   SUM(CASE WHEN ex_type='Debit' THEN `sum` ELSE 0 END) as Debit,
   SUM(CASE WHEN ex_type='Credit' THEN `sum` ELSE 0 END) as Credit
FROM acc 
Where etc...

答案 3 :(得分:1)

我不是MySQL专家,但您可能想尝试以下

SELECT 
  SUM(CASE WHEN ex_type='Debit' THEN sum ELSE 0 END CASE) as SumOfDebit,
  SUM(CASE WHEN ex_type='Credit' THEN sum ELSE 0 END CASE) as SumOfCredit,
FROM acc
WHERE
  month = '$month'

MySQL reference 5.0处理CASE语句,如果这不能按预期工作

答案 4 :(得分:0)

SELECT
    SUM(sum) as total
    SUM(IF(ex_type='Debit',sum,0)) Debit
    SUM(IF(ex_type='Credit',sum,0)) Credit
FROM acc 
WHERE month='$month'

答案 5 :(得分:0)

最简单(也是最酷)的方式是:

SELECT 
  SUM((ex_type='Debit') * sum) Debit,
  SUM((ex_type='Credit') * sum) Credit,
FROM acc
WHERE month = '$month'

这是有效的,因为在mysql中,true为1,false为0。