由于where和group by,子查询返回的值超过1

时间:2016-09-27 16:33:59

标签: sql group-by where aggregate-functions

我想制作一个简单的视图,以便查看来自不同仓库的库存总和是否> 0且<该产品的最低库存量。

以下是代码:

SELECT a.code, a.description, a.stk_min , b.Stk_Qty
FROM a 
INNER JOIN b ON a.code = b.productcode
WHERE a.stk_min > 0 and 

     (SELECT SUM(b.Stk_Qty )
     FROM b
     INNER JOIN a ON a.code = b.productcode
     Group By a.code) <= a.stk_min

当然我收到了错误

  

子查询返回的值超过1。当子查询跟随=!=<<=>>=或子查询被用作子查询时,不允许这样做表达。

我有什么办法可以改变这个吗?

2 个答案:

答案 0 :(得分:0)

您正在寻找相关子查询,而不是group by。此查询应该可以解决问题:

SELECT a.code, a.description, a.stk_min , b.Stk_Qty
FROM a JOIN
     b
     ON a.code = b.productcode
WHERE a.stk_min > 0 and 
      (SELECT SUM(b.Stk_Qty )
       FROM b2 
       WHERE a.code = b2.productcode
      ) <= a.stk_min;

我怀疑你想要这个:

SELECT a.code, a.description, a.stk_min, SUM(b.Stk_Qty)
FROM a LEFT JOIN
     b
     ON a.code = b.productcode
WHERE a.stk_min > 0
GROUP BY a.code, a.description, a.stk_min
HAVING COALESCE(SUM(b.Stk_Qty), 0) < a.stk_min;

答案 1 :(得分:0)

怎么样?
SELECT a.code, a.description, a.stk_min, SUM(b.Stk_Qty) SumQty
FROM a join b on b.productcode = a.code 
group by a.code, a.description, a.stk_min
Where a.stk_min > 0
Having   SUM(b.Stk_Qty) <= a.stk_min