简体   繁体   English

基于两列动态值的一列的总和

[英]Sum of one column based on two columns of dynamically value

I have following mysql table: 我有以下mysql表:

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. 我想要项目代码和仓库重复他们的总数时的总和 :例如:itm001 abc重复两次它们的总和显示itm001 = 70相同的方式为itm002并显示总和itm002 = 30。

I dont want static where clause (where item code = 'itm001' and warehouse = 'abc' or item code ='itm002' and warehouse = 'xyz'). 我不想要静态where子句(其中item code ='itm001'和warehouse ='abc'或item code ='itm002'和warehouse ='xyz')。

You should use GROUP BY with HAVING : 你应该使用GROUP BYHAVING

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. HAVING过滤掉仅在仓库中存在一次的项目。

尝试这个:

  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. 您可以在组中使用havin子句。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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