Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何在一个查询中编写两个不同条件的求和查询?_Mysql_Aggregate Functions - Fatal编程技术网

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

我有一个MySQL数据表
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