Mysql 如何在一个查询中编写两个不同条件的求和查询?
我有一个MySQL数据表Mysql 如何在一个查询中编写两个不同条件的求和查询?,mysql,aggregate-functions,Mysql,Aggregate Functions,我有一个MySQL数据表items,如下所示: +----+-------+----------+----------+ | id | value | discount | type | +----+-------+----------+----------+ | 1 | 20 | 1 | hardware | | 2 | 40 | 0 | hardware | | 3 | 60 | 1 | software | | 4
items
,如下所示:
+----+-------+----------+----------+
| id | value | discount | type |
+----+-------+----------+----------+
| 1 | 20 | 1 | hardware |
| 2 | 40 | 0 | hardware |
| 3 | 60 | 1 | software |
| 4 | 30 | 1 | software |
+----+-------+----------+----------+
当折扣
为1时,这意味着值实际上为零
我想得到以下结果
+----------+----+
| software | 0 |
| hardware | 40 |
+----------+----+
我知道如何在多个查询中执行此操作
SELECT type, SUM(value) from items where discount != 1 group by type
这让我觉得
+----------+----+
| hardware | 40 |
+----------+----+
然后
SELECT type, 0 from items where discount = 1 group by type
这让我
+----------+----+
| software | 0 |
| hardware | 0 |
+----------+----+
然后我需要连接这两个表以得到最终结果
我的问题是:
有没有一种方法可以只用一个查询就得到相同的结果
谢谢。我想这就是你想要的
SELECT type, SUM(if(discount =1, 0,value)) from items group by type