如何联接2个具有子查询的表?

时间:2018-07-15 17:19:40

标签: sql-server

select max(quantity) as Quantity, [Stock ID]
from (select sum(quantity) as quantity, StockID as "Stock ID"
      from Orders
      group by StockID) as quantity
group by [Stock ID]

我想获得最大存货总额。在from子句中有一个子查询是唯一对我有用的东西。现在,我想显示股票的ID,但不能显示。此代码为所有行提供了正确的解决方案。我只需要一行包含数量和ID。是我可以解决这个问题的另一种方法吗?

1 个答案:

答案 0 :(得分:0)

不需要外部最大值和group by,因为对于StockId的内部查询只有一行,因为已经有一个group max。因此,如果执行MAX,则每个StockId最多只能获得1行,这与值本身相同。

假设@StockId是一个参数,您所需要做的只是这个

select sum(quantity) as quantity, StockID as "Stock ID"
  from Orders where StockId=@StockId
  group by StockID