TSQL汇总帐户,最简洁的方法是什么?

时间:2010-07-03 00:23:47

标签: tsql sum

我想通过帐户,费用和&每个帐户的收入。收入和收入都有倍数。每个帐户的费用。我正在努力解决这个问题,因为我还在学习SQL,并认为其他人可能已经解决了这个问题?我肯定会感谢你的帮助!

我知道这个SQL服务器代码不正确,但它至少可以让我更清楚地了解我正在尝试做什么。

IF(SELECT(OBJECT_ID('TEMPDB .. #Total')))IS NOT NULL DROP TABLE #Total

声明@Expenses decimal(13,2),       @income decimal(13,2)

设置@expenses = sum(EXP_CHILD_CARE_AMOUNT)                 + sum(EXP_FOOD_AMOUNT)                 + sum(EXP_LIFE_INSURANCE_AMOUNT)                 + sum(EXP_TRANSPORTATION_AMOUNT)             + sum(EXP_TUITION_AMOUNT)                 + sum(EXP_USER_2_AMOUNT)             + sum(EXP_USER_3_AMOUNT)                 + sum(EXP_UTILITIES_AMOUNT)

设置@income =(总和(NET_PAY_AMOUNT)                 + sum(OTHER_INCOME_AMOUNT)

选择F.LOAN_NUMBER,@收件人,@ Expenses

INTO #Total 来自OPENQUERY(SvrLink,'

SELECT F.Account,@ Submit,@ Expenses

来自财务部门F.         内部联接帐户a(a.Account = f.Account)            其中a.balance> 0

仅与UR'争夺

1 个答案:

答案 0 :(得分:0)

...好吧,假设某些字段被分组到同一个表中(如果不是,您只需编写连接),您只需要1个查询。 (我希望所有语言都简洁......) @AccountId是您想要的帐户ID。

SELECT l.LOAN_NUMBER, l.AccountId,
    (SELECT sum(EXP_CHILD_CARE_AMOUNT) + sum(EXP_FOOD_AMOUNT) + 
      sum(EXP_LIFE_INSURANCE_AMOUNT) + sum(EXP_TRANSPORTATION_AMOUNT) + 
      sum(EXP_TUITION_AMOUNT) + sum(EXP_USER_2_AMOUNT) + 
      sum(EXP_USER_3_AMOUNT) + sum(EXP_UTILITIES_AMOUNT) 
      as ExpenseTotal FROM Expenses_Guessing_The_Table_Name
      WHERE AccountId = @AccountId) as ExpenseTotal,
    (SELECT sum(NET_PAY_AMOUNT) + sum(OTHER_INCOME_AMOUNT) as IncomeTotal
      FROM Income_Guessing_The_Table_Name
      WHERE AccountId = @AccountId) as IncomeTotal
    FROM Loans l 
    WHERE  l.AccountId = @AccountId AND l.Balance > 0