2012-07-07 42 views
0

我需要您來幫助我從一張表中爲金融交易及其行提取查詢,如下所示: 帳號:例如(4568643) Transactionamount:例如(1000美元) Kindoftransaction(借記卡或信用卡) transactionfile(並且這個數字保持和後鏈接到該交易的文件編號)使用不同總和和減法函數的sql查詢

我需要你的幫助,以提取查詢每一個(transactionfile的淨餘額)全部 (Transactionamount )從(Kindoftransaction)中持有「信用」,並從All(Transactionamount)的總和中扣除「借方」,其中 ( Accountnumber)是(4568643)

回答

0
select transactionfile, sum(case when kindoftransaction = 'debit' then -1 else 1 end * transactionamount) 
from financial 
where accountnumber = 4568643 
group by transactionfile 
+0

親愛的請注意,結果是好的,但我錯過了顯示(交易文件) – 2012-07-08 06:26:12

+0

編輯請求。 – shawnt00 2012-07-08 06:40:24

+0

很多人非常感謝我的朋友 – 2012-07-08 06:59:21

0

這有幫助嗎? - 注意它幫助,如果你可以發佈你的表定義

DECLARE @transactions TABLE 
(
    [AccountNumber] INT NOT NULL, 
    [TransactionAmount] DECIMAL(18, 10) NOT NULL, 
    [KindOfTransaction] CHAR(1) NOT NULL, -- this could be better served as a boolean/bit field 
    [TransactionFile] INT NOT NULL 
) 

-- dummy data 
INSERT INTO @transactions VALUES(4568643, 100, 'C', 123) 
INSERT INTO @transactions VALUES(4568643, 150, 'C', 124) 
INSERT INTO @transactions VALUES(4568643, 50, 'D', 125) 
INSERT INTO @transactions VALUES(2345623, 100, 'C', 126) 
INSERT INTO @transactions VALUES(2345623, 79, 'C', 127) 

    -- here's the actual query to return your data using a common table expression 
;WITH cteAccountSummary (AccountNumber, TotalCredits, TotalDebits) AS (
    SELECT [AccountNumber], 
      SUM(
       CASE [KindOfTransaction] 
        WHEN 'C' THEN [TransactionAmount] 
        ELSE 0 
       END 
      ), 
      SUM(
       CASE [KindOfTransaction] 
        WHEN 'D' THEN [TransactionAmount] 
        ELSE 0 
       END 
      ) 
    FROM @transactions 
    GROUP BY [AccountNumber] 
) 
SELECT [AccountNumber], TotalCredits - TotalDebits AS 'NetFinancialPosition' 
FROM cteAccountSummary 
+0

月1日我要感謝你的答案,但因爲它顯示 – 2012-07-07 23:25:30

+0

在一個行,如果可以,請重新輸入查詢這證明了我有很多很多空間 – 2012-07-07 23:26:13

+0

我不能有任何結果可以請你再次指定查詢...謝謝 – 2012-07-08 06:44:38