MySQL使用group by语句比较两个字段的总和

时间:2016-08-31 09:25:57

标签: mysql group-by sum

在表格下方,我希望这些发票的所有项目都是 包装

表格

mysql> select * from allotment;

+----+------------+---------+-----------+------------+------------+
| id | invoice_id | item_id | total_qty | packed_qty | created    |
+----+------------+---------+-----------+------------+------------+
|  1 |          4 |      26 |         4 |          4 | 2016-08-31 |
|  2 |          4 |      38 |         1 |          1 | 2016-08-31 |
|  3 |          5 |      39 |        16 |          8 | 2016-08-31 |
|  4 |          5 |       2 |         2 |          5 | 2016-08-31 |
+----+------------+---------+-----------+------------+------------+

我的查询:

mysql> SELECT invoice_id, created FROM allotment  
where sum(allotment.total_qty)=sum(allotment.packed_qty) 
GROUP BY invoice_id;

[**ERROR 1111 (HY000): Invalid use of group function]

我已经应用了很多方法,但它没有用。其实我需要比较一下 "sum of total_qty""sum of packed_qty"针对此问题 "invoice_id"

我的预期结果:

+------------+------------+
| invoice_id | created    |
+------------+------------+
|          4 | 2016-08-31 |

Logic: Invoice_id 4, total_item = 4+1 and total_packed= 4+1 
[select where total_item==total_packed]

有没有办法从“分配”表中获得此结果?

2 个答案:

答案 0 :(得分:2)

你需要使用HAVING,而不是WHERE

var parsedHTML = $.load(body);
console.log("the value");

MySQL HAVING子句,用于为行或聚合组指定过滤条件。

答案 1 :(得分:2)

试试这个

SELECT a1.invoice_id, a1.created FROM allotment AS a1
WHERE (SELECT SUM(a2.total_qty) FROM allotment AS a2 WHERE a2.invoice_id = a1.invoice_id) =  (SELECT SUM(a2.packed_qty) FROM allotment AS a2 WHERE a2.invoice_id = a1.invoice_id)  
GROUP BY invoice_id;