我有一组用于维护银行账户交易历史的表格。
我们已对交易应用分组并获取分组交易。这适用于普通帐户。我使用此查询来分析用户定期交易,这些交易发生在每周或每两周或每月的模式上,用于查找用户的工资信贷和生活费用。
当交易基于联合账户时,如果图形化交易在同一天发生,且描述相同,则查询总结错误。
例如:
丈夫&妻子在同一家公司工作,并获得1000及以上的薪酬。分别为500。分组应分别对1000组和500组。交易金额可能不同,因为他或她可以获得可变薪酬。由于这个问题,计算模式是错误的。如果它是两周一次,它计算为每周。有人可以解决这个问题。
要求是,如果一个组在同一天出现两次,它应该分别对它们进行分组。
SCHEMA
1. CustomerBankAccountTransactions
Column_name Type
---------------------------- ---------
BankAcounttransactionID nvarchar
BankAccountID nvarchar
TransactionDate datetime
Amount float
IsDebit nvarchar
RunningBalance nvarchar
Description ntext
2. CustomerBankTransactionGroupLink
Column_name Type
-------------------------- --------
ID numeric
TransactionGroupID numeric
BankAcountTransactionID nvarchar
UpdateUser nvarchar
UpdateDateTime datetime
3. CustomerTransactionGroup
Column_name Type
------------------- --------
ID numeric
SubCategoryID numeric
GroupName nvarchar
UpdateUser nvarchar
UpdateDateTime datetime
IsDebit nvarchar
查询示例是,
SELECT MAX(tg.ID),
tg.GroupName,
COUNT(tg.GroupName) AS GroupCount,
CASE
WHEN at.IsDebit = 't'
THEN 'Debit'
ELSE 'Credit'
END AS TransactionType,
MIN(at.Amount) AS MinimumAmount,
MAX(at.Amount) AS MaximumAmount,
AVG(at.Amount) AS AverageAmount,
MIN(at.TransactionDate) AS FirstTransacionDate,
MAX(at.TransactionDate) AS LastTransacionDate,
CASE
WHEN COUNT(at.TransactionDate) <= 1
THEN DATEDIFF(DAY, MIN(at.TransactionDate),
MAX(at.TransactionDate))
ELSE (DATEDIFF(DAY, MIN(at.TransactionDate),
MAX(at.TransactionDate)) / (COUNT(at.TransactionDate) - 1))
END AS TransactionInterval,
DATEDIFF(DAY, MAX(at.TransactionDate), GETDATE()) AS DaysSinceLastTransaction,
DATEDIFF(DAY, MIN(at.TransactionDate), MAX(at.TransactionDate)) AS TimeSpan
FROM CustomerBankAccountTransactions AT
INNER JOIN CustomerBankTransactionGroupLink atgl
ON atgl.BankAcountTransactionID = AT.BankAcounttransactionID
INNER JOIN CustomerTransactionGroup tg
ON tg.ID = atgl.TransactionGroupID
WHERE AT.BankAccountID = '012083191715294f957d06e-76ad-485a-ad0e-e115a1e479fe'
GROUP BY tg.GroupName,
AT.IsDebit
ORDER BY tg.GroupName