-
Notifications
You must be signed in to change notification settings - Fork 0
/
Aging.Sql
96 lines (96 loc) · 3.34 KB
/
Aging.Sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
WITH testing
AS (SELECT [itemid],
t2.inventsiteid,
[datephysical],
[qty],
[costamountposted],
[invoiceid],
[voucher],
[dateexpected],
[datefinancial],
[costamountphysical],
[statusreceipt],
[packingslipreturned],
[invoicereturned],
[packingslipid],
[voucherphysical],
[costamountadjustment],
[shippingdaterequested],
[shippingdateconfirmed],
[valueopen],
[datestatus],
[costamountstd],
[dateclosed],
[pickingrouteid],
[costamountoperations],
[returninventtransorigin],
t1.[inventdimid],
[markingrefinventtransorigin],
[inventdimfixed],
[dateinvent],
[inventtransorigin],
[nonfinancialtransferinventclosing],
t1.[modifieddatetime],
t1.[dataareaid],
t1.[recversion],
t1.[partition],
t1.[recid]
FROM [MITAX_live].[dbo].[inventtrans] AS t1
LEFT JOIN inventdim AS t2
ON t1.inventdimid = t2.inventdimid
AND t1.dataareaid = t2.dataareaid
-- here limiting physical date is important as this query will subtract stock from date after this date as well. like stock of 1/1/20 will also included in Feb data.
WHERE t1.dataareaid = 'companyname'
AND datephysical <> ''
AND datephysical <= '2019-12-31'),
ctern
AS (SELECT itemid,
inventsiteid,
datephysical,
qty,
Row_number()
OVER (
partition BY inventsiteid, itemid
ORDER BY datephysical) AS rn
FROM testing),
cte
AS (SELECT itemid,
inventsiteid,
datephysical,
qty,
Sum(CASE
WHEN qty < 0 THEN -1 * qty
ELSE 0
END)
OVER(
partition BY inventsiteid, itemid) AS QTYRemoved,
Sum(CASE
WHEN qty > 0 THEN qty
ELSE 0
END)
OVER(
partition BY inventsiteid, itemid
ORDER BY rn) AS QTYRecieved
FROM ctern),
af
AS (SELECT itemid,
inventsiteid,
datephysical,
qty,
CASE
WHEN qty > 0
AND qtyrecieved <= qtyremoved THEN 0
WHEN qty > 0
AND qty + qtyremoved > qtyrecieved THEN
qtyrecieved - qtyremoved
WHEN qty > 0 THEN qty
ELSE NULL
END AS RemainingQty
FROM cte)
SELECT itemid,
inventsiteid,
datephysical,
qty,
remainingqty
FROM af
WHERE remainingqty <> 0