在单个 MySQL 查询中,根据条件执行求和和减法?
为此,为求和和减法使用 CASE 语句和集合。我们首先创建一个表 −
mysql> create table DemoTable866( Status varchar(100), Amount int ); Query OK, 0 rows affected (0.63 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable866 values('ACTIVE',50); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable866 values('INACTIVE',70); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable866 values('INACTIVE',20); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable866 values('ACTIVE',100); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable866 values('ACTIVE',200); Query OK, 1 row affected (0.11 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable866;
这将生成以下输出 −
+----------+--------+ | Status | Amount | +----------+--------+ | ACTIVE | 50 | | INACTIVE | 70 | | INACTIVE | 20 | | ACTIVE | 100 | | ACTIVE | 200 | +----------+--------+ 5 rows in set (0.00 sec)
以下是使用单个 MySQL 查询在同一列中执行求和或减法的查询 −
mysql> select sum(CASE WHEN Status = 'ACTIVE' then Amount WHEN Status = 'INACTIVE' then -Amount END) AS RemainingAmount from DemoTable866;
这将生成以下输出 −
+-----------------+ | RemainingAmount | +-----------------+ | 260 | +-----------------+ 1 row in set (0.06 sec)
广告