-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFIFO_new.sql
More file actions
116 lines (102 loc) · 2.97 KB
/
FIFO_new.sql
File metadata and controls
116 lines (102 loc) · 2.97 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
DECLARE @tblInp TABLE (
[Code] NVARCHAR(128),
[Date] DATETIME,
[Quantity] INT
);
DECLARE @tblOut TABLE (
[Code] NVARCHAR(128),
[Date] DATETIME,
[Quantity] INT
);
-- Dữ liệu mẫu
INSERT INTO @tblInp ([Code], [Date], [Quantity]) VALUES
('INP1','2024-04-06', 100),
('INP2','2024-04-22', 50),
('INP3','2024-05-11', 170),
('INP4','2024-11-30', 150);
INSERT INTO @tblOut ([Code], [Date], [Quantity]) VALUES
('OUT1','2024-04-29', 150),
('OUT2','2024-06-24', 160),
('OUT3','2024-12-16', 150);
WITH InputSorted AS (
SELECT
CAST(ROW_NUMBER() OVER(ORDER BY Date, Code) AS INT) AS in_rn,
*
FROM @tblInp
),
OutputSorted AS (
SELECT
CAST(ROW_NUMBER() OVER(ORDER BY Date, Code) AS INT) AS out_rn,
*
FROM @tblOut
),
FIFO_Calculation AS (
-- Anchor member
SELECT
1 AS RowNumber,
in_rn,
Quantity AS in_remaining,
0 AS out_rn,
0 AS out_remaining,
0 AS assigned
FROM InputSorted
WHERE in_rn = 1
UNION ALL
-- Recursive member
SELECT
rec.RowNumber,
rec.in_rn,
CASE WHEN rec.in_remaining > rec.out_remaining THEN rec.in_remaining - rec.out_remaining
ELSE 0
END in_remaining,
rec.out_rn,
CASE WHEN rec.out_remaining > rec.in_remaining THEN rec.out_remaining - rec.in_remaining ELSE 0 END out_remaining,
CASE WHEN rec.in_remaining > rec.out_remaining THEN rec.out_remaining ELSE rec.in_remaining END assigned
FROM (
SELECT
cur.RowNumber + 1 RowNumber,
inp.in_rn,
CASE WHEN cur.isNextInp = 1 THEN inp.Quantity ELSE cur.in_remaining END in_remaining,
ot.out_rn,
CASE WHEN cur.isNextOut = 1 THEN ot.Quantity ELSE cur.out_remaining END out_remaining
FROM (
SELECT
RowNumber,
CASE WHEN in_remaining = 0 THEN 1
ELSE 0
END isNextInp,
CASE WHEN in_remaining = 0 THEN in_rn+1
ELSE in_rn
END in_rn,
in_remaining,
CASE WHEN out_remaining = 0 THEN 1
ELSE 0
END isNextOut,
CASE
WHEN out_remaining = 0 THEN out_rn+1
ELSE out_rn
END out_rn,
out_remaining
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY RowNumber DESC) LastRowNumber,
*
FROM FIFO_Calculation
) w
WHERE w.LastRowNumber = 1
) cur
JOIN InputSorted inp ON cur.in_rn = inp.in_rn
JOIN OutputSorted ot ON cur.out_rn = ot.out_rn
) rec
)
SELECT
inp.[Date] AS InputDate,
inp.[Code] AS InputCode,
ott.[Date] AS OutputDate,
ott.[Code] AS OutputCode,
v.assigned,
v.in_remaining,
v.out_remaining
FROM FIFO_Calculation v
JOIN InputSorted inp ON v.in_rn = inp.in_rn
JOIN OutputSorted ott ON v.out_rn = ott.out_rn
ORDER BY v.RowNumber;