如何在此查询选择上返回最小日期

时间:2016-01-22 22:43:49

标签: sql-server-2012

以下是查询:

  -- Get purchase order ETA for first purchase order whose quantity completes a (running total) sum (within the interval between today's date and some future date) adequate to satisfy current demand
  select min(t2.docduedate) as ETA
  from por1 t1
    inner join opor t2 on t1.docentry = t2.docentry
      join opor t3 on t2.docentry = t3.docentry
        and t3.docduedate <= t2.docduedate
  where t1.itemcode = 'NSL1705-S'
    and t2.docduedate > getdate()
  group by t1.itemcode
  --         , t1.dscription
          , t2.docduedate
  having (select sum(t6.quantity)
            from por1 t6
              inner join opor t7 on t6.docentry = t7.docentry
            where t7.docduedate <= t2.docduedate
              and t7.docduedate > getdate()
              and t6.itemcode = 'NSL1705-S') >= 141

结果如下:

ETA
2016-02-17 00:00:00.0
2016-02-24 00:00:00.0
2016-03-02 00:00:00.0
2016-04-11 00:00:00.0

我希望它只返回带有最小日期的行:

ETA
2016-02-17 00:00:00.0

我错过了什么? &#39; min(t2.docduedate)&#39;显然没有按照我希望的方式工作。

注意:这实际上是一个子查询,作为更大查询的一部分,所以我不能使用任何不能在子查询中使用的东西来解决这个问题。

更新(感谢500内部服务器错误),这有效:

  select min(t2.docduedate) as ETA
  from por1 t1
    inner join opor t2 on t1.docentry = t2.docentry
      join opor t3 on t2.docentry = t3.docentry
        and t3.docduedate <= t2.docduedate
  where t1.itemcode = 'NSL1705-S'
    and t2.docduedate > getdate()
    and (select sum(t6.quantity)
            from por1 t6
              inner join opor t7 on t6.docentry = t7.docentry
            where t7.docduedate <= t2.docduedate
              and t7.docduedate > getdate()
              and t6.itemcode = 'NSL1705-S') >= 141

0 个答案:

没有答案