窗口函数不能在另一个窗口函数或聚合的上下文中使用

时间:2016-08-04 09:46:44

标签: sql sql-server

     @date1 Date = '2011-06-01'
   ,@date2 Date ='2016-06-30'
   ,@StoreNo Nvarchar(Max)=' '
As 
Begin
Select 
       STD.StoreNo As StoreNo
       ,CheckDate As CheckDate
      ,ProductBarCode as ProductBarCode
     ,  SUM( case
    when Lead(STD.StockTakingQty) over ( order by STD.StockTakingQty) is null  
        and [CheckDate] <> EOMONTH([CheckDate])
      then STD.[StockTakingQty]
    else STD.[StockTakingQty] - lead(STD.[StockTakingQty]) over ( order by STD.StockTakingQty)
  end)AS ProducQty
    Into ##temp
     From StockTakingDetail STD
Inner Join
(Select StoreNo,CheckNo,CheckDate 
              From StockTakingMain SM )StocktakingMain 
   On STD.CheckNo =StockTakingMain.CheckNo

   Where  
  CheckDate Between @date1 AND @date2 

  Group by 
        STD.StoreNo,ProductBarCode,CheckDate

If EXISTS (Select StoreNo from ##temp)

Begin 

Declare @sql Nvarchar(max)
SET @sql = N'Select * from ##temp where 1=1 ' +@StoreNo+ 'Order By StoreNo,ProductBarcode'
EXECUTE sp_executesql @sql
END

Else 

BEGIN
SELECT
      ' ' as StoreNo
      ,'' as CheckDate
      ,'' as ProductBarCode
      ,0 as ProductQty

End

DRop Table ##temp

End

我正在尝试每日库存和每个月一旦你拿走库存但我必须显示每天库存不能留下那里的空值。

1 个答案:

答案 0 :(得分:0)

您正试图在LEAD内使用SUM - 这就是您收到错误的原因。而不是LEAD使用OUTER APPLY来获取您需要的下一个值。

Select  STD.StoreNo As StoreNo,
        CheckDate As CheckDate,
        ProductBarCode as ProductBarCode,
        SUM(case 
                when s.StockTakingQty is null and [CheckDate] <> EOMONTH([CheckDate])
                then STD.[StockTakingQty]
                else STD.[StockTakingQty] - s.StockTakingQty
            end) AS ProducQty
Into ##temp
From StockTakingDetail STD
Inner Join (
    Select  StoreNo,
            CheckNo,
            CheckDate 
    From StockTakingMain SM
    )StocktakingMain 
    On STD.CheckNo =StockTakingMain.CheckNo
OUTER APPLY (
    SELECT TOP 1 * 
    FROM StockTakingDetail
    WHERE SomeIDfield = STD.SomeIDfield
    ORDER BY StockTakingQty 
    ) s
Where CheckDate Between @date1 AND @date2 
Group by STD.StoreNo,ProductBarCode,CheckDate