我有两张表Table1
和Table2
Table1
Amount Account_Key Branch
==================================
7719499.00 102 150
8148812.51 101 150
351200.00 101 150
267240.00 102 150
327750.00 102 150
150400.00 101 150
176310.00 101 150
265591.00 102 150
153055.00 102 150
256449.00 101 150
242095.00 101 150
244000.00 102 150
247980.00 101 150
175997.00 102 150
. . .
. . .
. . .
现在我需要一个查询来获取Table1
按GLDescription
分组的所有记录的总和,并检查Table2 Fromaccount,ToAccount,IncludeAccount,ExcludeAccount
为此,我写了一个查询:
SELECT T2.gldescriptionid,
T2.gldescription,
T2.fromaccount,
T2.toaccount,
(SELECT Sum(amount)
FROM table1 T1 WITH(nolock)
WHERE ( T1.account_key BETWEEN T2.fromaccount AND T2.toaccountaccount )
)AS
Amount
FROM table2 T2 WITH(nolock)
GROUP BY T2.gldescriptionid,
T2.gldescription,
T2.fromaccount,
T2.toaccount
ORDER BY T2.gldescriptionid
我生成的结果是: Resultant Table
这是FromAccount
和ToAccount
T1.Account_Key
和T2.FromAccount
T2.ToAccountAccount
条件的结果
现在我需要一个查询来生成所有条件FromAccount,ToAccount,IncludeAccount,ExcludeAccount
获取FromAccount和ToAccount之间所有帐户的总和,并减去ExcludeAccount列中存在的所有帐户的总和,并添加总和 IncludeAccount列中的所有帐户
我正在使用Function将逗号分隔的id的字符串从Table2转换为表
select data from dbo.split('102,200,56', ',')
这将生成如下输出:
data
------
23
45
2
答案 0 :(得分:0)
我认为数据结构会给你带来麻烦;性能会受到影响,但如果你想改变那可能是另一个问题的主题。目前,您只需要一个返回正确数据的查询。
请尝试以下方法:
-
请注意,我假设您的Select t2.GLDescriptionID,
t2.GLDescription,
t2.FromAccount,
t2.ToAccount,
Sum(t1.Amount) As Amount
From Table1 As t1
Join Table2 As t2
On -- Condition for account
((t1.Account_Key >= t2.FromAccount
And t1.Account_Key <= t2.ToAccount
And Not Exists (Select 1 From dbo.Split(t2.ExcludeAccounts) As x Where Try_Convert(int, x.data) = t1.Account_Key))
Or Exists (Select 1 From dbo.Split(t2.IncludeAccounts) As i Where Try_Convert(int, y.data) = t1.Account_Key)))
And -- Condition for branch
((t1.Branch >= t2.FromBranch
And t1.Branch <= t2.ToBranch
And Not Exists (Select 1 From dbo.Split(t2.ExcludeBranches) As x Where Try_Convert(int, x.data) = t1.Branch))
Or Exists (Select 1 From dbo.Split(t2.IncludeBranches) As i Where Try_Convert(int, y.data) = t1.Branch)))
Group By t2.GLDescriptionID, t2.GLDescription, t2.FromAccount, t2.ToAccount
Order By t2.GLDescriptionID;
和Table1.Account_Key
字段都是Table1.Branch
数据类型,而不是某些文本字段或其他内容。
如果您完全关心正确的答案,请不要使用NOLOCK
。