需要查询以从Tabl1中选择数据,具体取决于表2中的条件

时间:2016-12-03 22:58:08

标签: sql sql-server

我有两张表Table1Table2

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
         .            .           .
         .            .           .
         .            .           .


This is Table2

现在我需要一个查询来获取Table1GLDescription分组的所有记录的总和,并检查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

这是FromAccountToAccount

之间只有一个T1.Account_KeyT2.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

1 个答案:

答案 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