使用Union创建查询的运行余额总计

时间:2016-12-01 15:31:40

标签: mysql sql

我们有一个跟踪客户奖励积分的网络应用程序。我们正在使用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

正如所建议的那样,我使用UNION来组合来自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。这可能吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;