过滤 Table 个结果 自连接

Filter Table results Self Join

想象一下包含收据信息的大型 table。由于它包含如此多的数据,因此您需要 return 数据的一个子集,尽可能排除或合并行。

这里是 SQL 和结果 table,展示了应该如何 returned 数据。

create table table1
(RecieptNo smallint, Customer varchar(10),  ReceiptDate date,
 ItemDesc varchar(10), Amount smallint)


insert into table1 values
(100, 'Matt','2022-01-05','Ball', 10),
(101, 'Mark','2022-01-07','Hat', 20),
(101, 'Mark','2022-01-07','Jumper', -20),
(101, 'Mark','2022-01-14','Spoon', 30),
(102, 'Luke','2022-01-15','Fork', 15),
(102, 'Luke','2022-01-17','Spork', -10),
(103, 'John','2022-01-20','Orange', 13),
(103, 'John','2022-01-25','Pear', 12)

如果同一张收据上有几行负值和正值抵消,则不要 return 任何一行。 如果有单据负数不超过正数,则负数从正数中扣除。

RecieptNo Customer ReceiptDate ItemDesc Amount
100 Matt 2022-01-05 Ball 10
101 Mark 2022-01-14 Spoon 30
102 Luke 2022-01-15 Fork 5
103 John 2022-01-20 Orange 13
103 John 2022-01-25 Pear 12

事实证明这很棘手,有什么想法吗?

根据您提供的 table,我想您只需要最早日期的行,因为您有多行具有相同的收据,在扣除后带来积极的 Amount

;WITH cte AS (
SELECT  *
,       SUM( amount) OVER (PARTITION BY RecieptNo ORDER BY RecieptNo, ReceiptDate ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS ActualAmount 
,       ROW_NUMBER() OVER (PARTITION BY RecieptNo ORDER BY RecieptNo, ReceiptDate) AS rn
FROM table1)
SELECT RecieptNo, Customer, ReceiptDate, ItemDesc, ActualAmount 
FROM cte 
WHERE ActualAmount > 0 AND rn = 1

了解 window 函数和 cte。