简体   繁体   中英

MySQL compare between sum of two fields with group by statement

Below from the table, I am expecting those invoice's all item are packed.

Table:

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 |
+----+------------+---------+-----------+------------+------------+

My query:

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]

I have applied many way but it didn't work. Actually I need to compare "sum of total_qty" and "sum of packed_qty" against same "invoice_id" .

My Expected result:

+------------+------------+
| 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]

Is there any way to get this result from the "allotment" table?

You need to use HAVING, not WHERE

SELECT invoice_id, created,sum(allotment.total_qty) t
 sum(allotment.packed_qty) p
FROM allotment  
GROUP BY invoice_id
Having t=p;

MySQL HAVING clause to specify a filter condition for groups of rows or aggregates.

Try this

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM