简体   繁体   中英

Sum of one column based on two columns of dynamically value

I have following mysql table:

item code | warehouse | qty
---------------------------  
itm001    |    abc    |10  
itm002    |    xyz    |20  
itm003    |    pqr    |20  
itm004    |    pqr    |15  
itm001    |    abc    |60  
itm002    |    xyz    |10  
itm004    |    tqr    |20  
itm003    |    www    |20  
itm001    |    ppp    |15  

I want sum of when item code and warehouse repeat their qty total : for example: itm001 abc is repeted two times their sum display itm001 = 70 same way for itm002 and display sum itm002 = 30.

I dont want static where clause (where item code = 'itm001' and warehouse = 'abc' or item code ='itm002' and warehouse = 'xyz').

You should use GROUP BY with HAVING :

SELECT itemcode,warehouse,SUM(qty) FROM yourtable
GROUP BY itemcode,warehouse
HAVING COUNT(*) > 1;

HAVING filters out the items that only exist once in a warehouse.

尝试这个:

  SELECT itemcode,warehouse,SUM(qty) FROM table1 GROUP BY warehouse,itemcode;

Use this :

SELECT item_code, warehouse,sum(qty)
FROM your_table
GROUP BY item_code, warehouse

You can use the havin clause on a group by.

select item_code, warehous, sum(qty), count(*)
group by item_code, warehouse 
having count(*) > 1

如果我理解正确,你可以使用: SELECT item_code, warehouse , SUM(qty) FROM yourTable WHERE (...) GROUP BY item_code, warehouse;

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