2014-11-04 75 views
0

我有一個交易表如下:Tr_No是主鍵在MSSQL SQL的Transact陳述或MYSQL

Tr_No Tr_Date  Tr_Remarks     Tr_Amt 
1  2014-05-05 Cash Deposited     1000 
2  2014-05-06 Credit Card Withdrawal   -250 
3  2014-05-07 ATM Withdrawal     -450 
4  2014-05-08 Cash Deposited     1000 

我需要一個表如下:

Date    Remarks    Cash Deposited Cash Withdrawal Balance 
2014-05-05  Cash Deposited   1000        1000 
2014-05-06  Credit Card Withdrawal      -250    750 
2014-05-07  ATM Withdrawal        -450    300 
2014-05-08  Cash Deposited   1000        1300 

我需要寫一個SQL查詢在MySQL或MSSQL中獲取上述表格。請幫助我,因爲我是SQL新手。使用Select語句在存儲過程中優先

+0

@TomTom感謝您的有效信息,但如果你能幫助我如何寫這個查詢這將是對我更有幫助..... – user3085636 2014-11-04 11:45:02

+1

不,不會。這個問題將被關閉,因爲我們不是一個代碼寫作服務。希望其他人做你的工作(包括學習和嘗試) - 僱用他們。首先閱讀網站規則,並在這裏不歡迎哪些問題。 – TomTom 2014-11-04 11:57:32

回答

0

試試這個。這應該給你一個想法。

CREATE TABLE #tt 
    (
    Tr_No  INT, 
    Tr_Date DATE, 
    Tr_Remarks VARCHAR(100), 
    Tr_Amt  INT 
) 

INSERT INTO #tt 
VALUES  (1,'2014-05-05','Cash Deposited',1000), 
      (2,'2014-05-06','Credit Card Withdrawal',-250), 
      (3,'2014-05-07','ATM Withdrawal',-450), 
      (4,'2014-05-08','Cash Deposited',1000); 

WITH cte 
    AS (SELECT *, 
       CASE WHEN Tr_Amt > 0 THEN CONVERT(VARCHAR(50), Tr_Amt) ELSE '' END [Cash Deposited], 
       CASE WHEN Tr_Amt < 0 THEN CONVERT(VARCHAR(50), Tr_Amt) ELSE '' END [Cash Withdrawal], 
       Tr_Amt Balance 
     FROM #tt) 
SELECT Tr_Date, 
     Tr_Remarks, 
     [Cash Deposited], 
     [Cash Withdrawal], 
     (SELECT Sum(Balance) Balance 
     FROM cte a 
     WHERE a.Tr_Date <= b.Tr_Date) AS Balance 
FROM cte b 

輸出

Tr_Date  Tr_Remarks    Cash Deposited Cash Withdrawal Balance 
---------- --------------   -------------- --------------- ------- 
2014-05-05 Cash Deposited   1000       1000 
2014-05-06 Credit Card Withdrawal     -250   750 
2014-05-07 ATM Withdrawal       -450   300 
2014-05-08 Cash Deposited   1000       1300 
+1

剛剛爲他們完成了某人的功課。沒有學到什麼 – Fred 2014-11-04 13:05:35