SQL - 检查字段值(金钱)是否为客户相等的值的 99%

SQL - Check if field value (money) is 99% of the value where customer is equal

请注意,我想编写一个具有以下条件的 SQL 查询。

检查是否有借方金额 = 在贷方金额的 (99% 和 101%) 之间(反之亦然) 客户是平等的,日期是今天

假设我有下面的 table:

Customer Debit Credit Amount Processing_Date
1001     D            100    01/12/2020
1001           C      100.02 01/12/2020
1002     D            102    01/12/2020
1002           C      102    01/12/2020
1004     D            106    01/12/2020
1004           C      135    01/12/2020
1005     D            111    01/12/2020
1006     D            123    01/12/2020

在这种情况下,我只想显示前 4 条记录。

有人可以建议 SQL 查询应该是什么样子才能获得这样的结果吗?

感谢您的宝贵时间。

您可以尝试以下方法来获取比率并过滤掉。我把今天的常数。您可以相应地使用 GETDATE().

DECLARE @table table(customerid int, debit char(1), credit char(1),
amt money, dateval date)

INSERT INTO @table
values
(1001,'D',null,100   ,'01/12/2020')
,(1001,null,'C',100.02,'01/12/2020')
,(1002,'D',null,102   ,'01/12/2020')
,(1002,null,'C',102   ,'01/12/2020')
,(1004,'D',null,106   ,'01/12/2020')
,(1004,null,'C',135   ,'01/12/2020')
,(1005,'D',null,111   ,'01/12/2020')
,(1006,'D',null,123   ,'01/12/2020');

;With cte_customerId as
(
select customerId
,sum(case when debit is not null then amt end) as debit
,sum(case when credit is not null then amt end) as credit
from @table
WHERE DATEVAL = '01/12/2020'
group by customerid
)
SELECT * FROM @table where customerid in
(
SELECT customerid FROM cte_customerId
where (credit/debit) between 0.99 and 1.01
or (debit/credit) between 0.99 and 1.01
)
+------------+-------+--------+--------+------------+
| customerid | debit | credit |  amt   |  dateval   |
+------------+-------+--------+--------+------------+
|       1001 | D     | NULL   | 100.00 | 2020-01-12 |
|       1001 | NULL  | C      | 100.02 | 2020-01-12 |
|       1002 | D     | NULL   | 102.00 | 2020-01-12 |
|       1002 | NULL  | C      | 102.00 | 2020-01-12 |
+------------+-------+--------+--------+------------+