尝试为 SQL Server 编写一个 T-SQL 查询,该查询采用
itemid
和 quantity summary
(始终 > 0)作为参数,并按日期降序选择与此摘要匹配的事务(包括具有剩余的行)减法)。
例如,如果我想选择数量为 10 的项目 1。脚本选择涵盖该金额的所有有序交易,即使总计超过 10 笔。(1 +> +3 > +0 > +10 > 停止!)
create table #items(itemid int, qtySum money)
insert into #items
values (1, 10), (2, 33), (3, 15), (4, 3),
(5, 3), (6, 15), (7, 15)
create table #transactions
(
itemid int,
trid int,
trdate date,
qty money
)
insert into #transactions
values (1, 1, '20240212', 1),
(1, 2, '20240211', 3),
(1, 3, '20240211', 0),
(1, 4, '20240210', 10),
(1, 5, '20240209', 10),
(1, 6, '20240208', 1),
(2, 7, '20240212', 22),
(2, 8, '20240211', 11),
(2, 9, '20240210', -5),
(2, 10, '20240210', -4),
(2, 11, '20240209', 9),
(2, 12, '20240209', 4),
(2, 13, '20240209', 6),
(3, 15, '20240212', 10),
(3, 16, '20240211', -2),
(3, 17, '20240210', -3),
(3, 18, '20240209', 8),
(3, 19, '20240208', 4),
(3, 20, '20240207', 2),
(4, 21, '20240212', 5),
(5, 22, '20240212', 3),
(5, 23, '20240211', 3),
(5, 24, '20240210', 3),
(7, 25, '20240212', 0)
我正在尝试使用 CTE,没有光标。
;WITH cte AS
(
SELECT
i.itemid, i.qtySum AS iQuantity,
tr.trid, tr.qty AS trQuantity,
SUM(tr.qty) OVER (PARTITION BY i.itemid ORDER BY tr.trdate desc ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS sum_amount
FROM
#items i
INNER JOIN
#transactions tr ON i.itemid = tr.itemid
)
SELECT *
FROM cte
WHERE sum_amount - iQuantity < trQuantity
UNION
SELECT i.itemid, i.qtySum, NULL, NULL, NULL
FROM #items i
WHERE NOT EXISTS (SELECT TOP 1 1 FROM cte c WHERE c.itemid = i.itemid)
DROP TABLE #items
DROP TABLE #transactions
我对第 2 项有疑问。
在我获得确切的金额后,摘要会下降,并选择其他行。
脚本选择id的7,8,10,11。但我只需要7,8
有谁知道如何解决这个问题吗?