@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
我正在尝试每日库存和每个月一旦你拿走库存但我必须显示每天库存不能留下那里的空值。
答案 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