SQL查询使用分组依据查找总和

时间:2019-01-29 18:38:44

标签: sql

仅当每个prodid中的数量大于1时,SQL查询才能找到相似prodid的数量总和。 SQL查询:

Select ProdID,sum(quantity) 
  From product 
 Where quantity >1 
 Group by ProdID

上述查询中存在哪些逻辑错误? enter image description here

结果应为:

ProdID  Quantity
------  --------
 102      11 

2 个答案:

答案 0 :(得分:2)

为此,还应在quantity表达式中的带有group by子句的having

Select ProdID,quantity
  from product 
 group by ProdID, quantity
 having sum(quantity) >1 

编辑由于您的最后评论):如下使用not in

Select ProdID, sum(quantity) 
  from product 
 where ProdID not in ( select ProdID from product p where quantity = 1 ) 
 group by ProdID

Rextester Demo

答案 1 :(得分:1)

您可以在having中使用过滤:

Select ProdID, sum(quantity)
from product
group by ProdID
having min(quantity) > 1;

使用min()假定quantity为非负数。