2010-07-03 53 views
0

我試圖按帳戶總計,費用爲&每個帳戶的收入。有多個帳戶收入的收入&。我仍在努力學習SQL,並認爲其他人可能已經解決了這個問題?我當然會感激的幫助!TSQL按帳戶總結,處理此問題的最簡潔方法是什麼?

我知道這個SQL服務器代碼是不正確的,但它至少給我一個更清晰的圖片我正在嘗試做什麼。

IF(SELECT(OBJECT_ID( 'TEMPDB ..#共')))IS NOT NULL DROP TABLE#合計

聲明@Expenses十進制(13,2), @income十進制(13,2)

組@expenses =總和(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) +總和(EXP_UTILITIE S_AMOUNT)

組@income =(SUM(NET_PAY_AMOUNT) + SUM(OTHER_INCOME_AMOUNT)

SELECT F.LOAN_NUMBER,@Income,@Expenses

INTO#合計 FROM OPENQUERY(SvrLink,'

SELECT f.Account,@Income,@Expenses

FROM財政˚F 內連接上(a.Account = f.Account) WHE一個帳戶再a.balance> 0

只獲取WITH UR「)

+0

你的表名是什麼? EXP_CHILD_CARE_AMOUNT和EXP_FOOD_AMOUNT列是否位於同一個表中?那麼NET_PAY_AMOUNT和OTHER_INCOME_AMOUNT呢? – Tahbaza 2010-07-03 00:45:15

回答

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 
+0

是的所有列都在同一個表中。第二個表只是爲了驗證帳戶仍然有一個balance.I會給這個旋轉,所以感謝幫助.. – JMS49 2010-07-03 01:06:26

+0

收到此錯誤: SQL0104N在「WHERE F.Loan_Number」後面找到一個意外的標記「as」。預期的令牌可能包括:「」。 SQLSTATE = 42601 – JMS49 2010-07-03 01:20:49

+0

這裏是代碼: SELECT LOAN_NUMBER, (SELECT SUM(EXP_CHILD_CARE_AMOUNT)+ SUM(EXP_FOOD_AMOUNT)+ 總和(EXP_LIFE_INSURANCE_AMOUNT)+ SUM(EXP_TRANSPORTATION_AMOUNT)+ 總和(EXP_TUITION_AMOUNT)+ SUM(EXP_USER_2_AMOUNT)+ 總和( EXP_USER_3_AMOUNT)+ SUM(EXP_UTILITIES_AMOUNT) 作爲ExpenseTotal FROM財務˚F WHERE F.Loan_Number如ExpenseTotal, (SELECT SUM(NET_PAY_AMOUNT)+ SUM(OTHER_INCOME_AMOUNT)作爲IncomeTotal FROM財務 WHERE L.Loan_Number作爲IncomeTotal FROM貸款大號 WHERE L.First_Principal_Balance> 0 – JMS49 2010-07-03 01:21:37

相關問題