Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 461
AHJeebon Avatar asked Oct 20 '25 03:10

AHJeebon


1 Answers

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.

like image 97
Abhishek Sharma Avatar answered Oct 21 '25 18:10

Abhishek Sharma