【发布时间】:2017-11-15 06:47:07
【问题描述】:
我有一个如下表结构 -
Account Number | Transaction Type | Amount | Date
交易类型可以是贷方或借方。我需要检查信用或借记交易金额是否大于某个阈值。如果是,请检查金额是否大于收入 * 10(存储在其他表中)。
可能有多种情况(考虑信用阈值 >= 10000,借记阈值 >= 20000,收入 = 1000)-
1. Account Number | Transaction Type | Amount | Date
A1 | Credit | 10000 | 11-11-2017
此示例中不存在借记行,但 A1 满足所有条件
2. Account Number | Transaction Type | Amount | Date
A2 | Debit | 20000 | 12-11-2017
本例中不存在 Credit 行,但 A2 满足所有条件
3. Account Number | Transaction Type | Amount | Date
A3 | Credit | 10000 | 13-11-2017
A3 | Debit | 5000 | 13-11-2017
此示例中同时存在贷方和借方行,但 A3 满足贷方条件
4. Account Number | Transaction Type | Amount | Date
A4 | Credit | 5000 | 14-11-2017
A4 | Debit | 20000 | 14-11-2017
此示例中同时存在贷方和借方行,但 A4 满足借方条件
5. Account Number | Transaction Type | Amount | Date
A5 | Credit | 10000 | 15-11-2017
A5 | Debit | 20000 | 15-11-2017
本例中 Credit 和 Debit 行都存在,但 A5 应满足 Debit 条件,因为它的值更大(本例需要取最大值)
6. Account Number | Transaction Type | Amount | Date
A6 | Credit | 10000 | 16-11-2017
A6 | Debit | 20000 | 16-11-2017
考虑本例中的收入 = 3000,本例中同时存在贷方和借方行,但 A6 不应满足任何条件,因为收入 *10 的值大于贷方/借方交易值。
我已经使用带有 LEFT & RIGHT 连接的 UNION 来查找 Credit/Debit 值,但要查找是否有更好的方法来编写此脚本。如果任何贷方/借方值不存在,则将其设为零。我使用的是 SQL Server 2012。
目前已开发(高水平)的脚本:
SELECT
temp.Number as Number,
temp.Amount1 as CrAmt,
temp.Amount2 as DrAmt
FROM
(
SELECT
t1.Account_Number AS Number,
t1.Amount AS Amount1,
isnull(t2.Amount, 0) as Amount2
FROM
TableName AS t1 WITH (NOLOCK) LEFT JOIN
TableName AS t2 WITH (NOLOCK) on isnull(t2.Transaction_Type, 'Debit') = 'Debit' and isnull(t2.Account_Number,t1.Account_Number) = t1.Account_Number
WHERE
t1.Transaction_Type = 'Credit'
UNION
SELECT
t1.Account_Number AS Number,
t1.Amount AS Amount1,
isnull(t2.Amount, 0) as Amount2
FROM
TableName AS t1 WITH (NOLOCK) RIGHT JOIN
TableName AS t2 WITH (NOLOCK) on isnull(t2.Transaction_Type, 'Debit') = 'Debit' and isnull(t2.Account_Number,t1.Account_Number) = t1.Account_Number
WHERE
t1.Transaction_Type = 'Credit'
) temp
where
(temp.Amount1 >= 10000 and temp.Amount1>= Income * 10) OR (temp.Amount2 >= 20000 and temp.Amount2>= Income * 10)
【问题讨论】:
-
它将帮助您提供脚本
-
是添加了脚本
-
我还没有完全得到你的脚本,但我高度怀疑它不是最佳的。您能否检查此查询并告诉其输出中存在哪些错误?
SELECT * FROM YourTable WHERE AccountNumber IN (SELECT DISTINCT AccountNumber FROM YourTable WHERE (TransactionType = 'Credit' AND Amount > @CreditThreshold AND Amount > @Income * 10) OR (TransactionType = 'Debit' AND Amount > @DebitThreshold AND Amount > @Income * 10)) -
这些只会给我帐号,而我希望借方和贷方交易值及其日期都在一行中
-
FWIW,以
SELECT * FROM YourTable开头,不能只给出账号。
标签: sql sql-server