2016-12-01 68 views
0

我們有一個跟蹤客戶獎勵積分的web應用程序。我們正在使用MySQL數據庫。 我本來是從一個單一的表餘額(RunningTotal)拖着走的數據並顯示點的數量在每次交易查詢的代碼如下:通過聯盟查詢創建運行餘額總計

SELECT DateSubmitted 
, PointTotal as Points 
, (SELECT SUM(PointTotal) 
     FROM ptrans_detail x 
      WHERE x.CustID = a.CustID 
      AND (x.DateSubmitted < a.DateSubmitted OR x.DateSubmitted = a.DateSubmitted)) AS RunningTotal 
, comment 
    FROM ptrans_detail a 
    WHERE CustID='10009' 
    Order by TransID Desc 

這工作得很好,直到它被發現有人未在ptrans_detail表中存在的一些條目,這個問題被張貼在這裏: Query Data from 2 MySQL tables with some duplicate records

至於建議,我用聯盟2個查詢從2個表結合起來,讓所有的記錄,查詢是:

SELECT CustID 
     , DateSubmitted 
     , Type 
     , Points 
      FROM `trans_summary` 
      WHERE CustID = '10009' 
UNION 

SELECT CustID 
, DateSubmitted 
, Type 
, PointTotal 
    FROM `ptrans_detail` 
     WHERE CustID = '10009' 
      and DateSubmitted NOT IN 
      (SELECT DateSubmitted FROM 
      `trans_summary` 
       WHERE CustID = '10009') 

這很好,但現在我想在第一個查詢中添加RunningTotal。這可能嗎?

+1

當然,考慮這整個語句作爲一個子查詢,在這裏做SELECT * FROM(您的工會查詢的運行總量外)。另外,mysql和sql server是不同的數據庫,你使用的是? –

+0

嗨Rich,我正在使用MySQL。 – danman280

回答

0

你想這樣的:

SELECT CustID, DateSubmitted, Type, SUM(Points) FROM (SELECT CustID 
      , DateSubmitted 
      , Type 
      , Points 
       FROM `trans_summary` 
       WHERE CustID = '10009' 
    UNION 

    SELECT CustID 
    , DateSubmitted 
    , Type 
    , PointTotal as Points 
     FROM `ptrans_detail` 
      WHERE CustID = '10009' 
       and DateSubmitted NOT IN 
       (SELECT DateSubmitted FROM 
       `trans_summary` 
        WHERE CustID = '10009')) AS tr_summery 
0

我會建議你使用union all,除非你真的需要union

獲得MySQL中的運行總和,最簡單的方法是使用變量:

SELECT t.*, 
     (@sump := if(@c = CustId, @sump + Points, 
        if(@c := CustId, Points, Points) 
        ) 
     ) as runningTotal 
FROM (SELECT CustID, DateSubmitted, Type, Points 
     FROM trans_summary 
     WHERE CustID = '10009' 
     UNION ALL -- Maybe it should be `UNION` 
     SELECT CustID, DateSubmitted, Type, PointTotal 
     FROM ptrans_detail 
     WHERE CustID = '10009' AND 
      DateSubmitted NOT IN (SELECT ts.DateSubmitted FROM trans_summary ts WHERE ts.CustID = '10009') 
    ) t CROSS JOIN 
    (SELECT @c := -1, @sump := 0) params 
ORDER BY CustId, DateSubmitted; 
+0

好吧,一些記錄在兩個表中都有重複,所以我只想顯示一次,我的印象是UNION ALL – danman280

+0

使用UNION實現的效果很好。我唯一的問題是,我想通過DateSubmitted Desc顯示(最新的記錄第一)。然而,運行總數是從最近的日期開始計算的,並且總計回來...我如何反轉這個數據,以便從最舊的DataSubmitted總數中總結出來? – danman280

+0

'ORDER BY CustId,DateSubmitted DESC'是否解決了問題? –