为MySQL中的每个SELECT字段设置WHERE子句的替代项
您可以使用CASE语句-
mysql> create table DemoTable1988 ( Value1 int, Value2 int, Price int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1988 values(10,7,500); mysql> insert into DemoTable1988 values(7,9,400); mysql> insert into DemoTable1988 values(8,7,200); mysql> insert into DemoTable1988 values(7,4,300);
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1988;
这将产生以下输出-
+--------+--------+-------+ | Value1 | Value2 | Price | +--------+--------+-------+ | 10 | 7 | 500 | | 7 | 9 | 400 | | 8 | 7 | 200 | | 7 | 4 | 300 | +--------+--------+-------+ 4 rows in set (0.00 sec)
这是对每个SELECT字段的WHERE子句的查询:
mysql> select sum( case when Value2=7 then Price else 0 end)- sum( case when Value1=7 then Price else 0 end) as Result from DemoTable1988;
这将产生以下输出-
+--------+ | Result | +--------+ | 0 | +--------+ 1 row in set (0.23 sec)
热门推荐
10 爸爸生日的祝福语简短
11 微信立冬祝福语简短
12 婚礼伴娘祝福语大全简短
13 考上大学简短祝福语、
14 给妈妈祝福语简短内容
15 生日高考祝福语妹妹简短
16 对情侣朋友祝福语简短
17 祝福语送超市同事简短
18 婚礼红包祝福语简短霸气