查询计数值减去的SQL

时间:2017-04-05 08:25:42

标签: mysql

我有一个数据库。包含几个表,有一个表名

  

stockdiary

,有一个字段

  

单元

示例:

**units**
-3
7
-8
-2
20

有负值和正值,如何查询仅对负值求和

2 个答案:

答案 0 :(得分:0)

SELECT SUM(units) 
FROM stockdiary
WHERE units < 0

答案 1 :(得分:0)

SELECT SUM(CASE WHEN units<0 THEN units ELSE 0 END) as NegativeTotal 
from stockdiary

OR

SELECT SUM(units) as NegativeTotal 
    from stockdiary where units<0