MYSQL中当前行之前(和包括)日期之前的所有行的总和

时间:2015-07-30 21:43:10

标签: mysql sql running-total

重要的是要知道在查询时间内日期是未知的,所以我不能只是硬编码一个' WHERE'子句。

这是我的表:

SELECT  Id, 
        Name, 
        [0] as UserType0, 
        [1] as UserType1 
FROM    (SELECT p.Id, p.Name, u.Name AS UserName, pm.MemberType
         FROM   Project as P
                LEFT JOIN ProjectMember as PM ON P.Id = PM.Project_Id
                LEFT JOIN [User] as U ON PM.User_Id = U.Id 
        ) q
PIVOT (
        MIN(UserName)
        FOR MemberType IN ([0],[1])
) p

这是所需的输出:

+-----------+----------+-------------+
| Date_ID   | Customer | Order_Count |
+-----------+----------+-------------+
| 20150101  | Jones    | 6           |
| 20150102  | Jones    | 4           |
| 20150103  | Jones    | 3           |
+-----------+----------+-------------+

我的猜测是我需要使用变量或者加入。

编辑:仍然无法让它足够快。很慢。

3 个答案:

答案 0 :(得分:2)

尝试此查询;在不限制您操作的数据集的情况下,它最有可能做到最好。它应该受益于索引(customer,date_id)。

select 
  t1.date_id, t1.customer, sum(t2.order_count)
from 
  table1 t1
left join 
  table1 t2 on t1.customer = t2.customer
           and t1.date_id >= t2.date_id
group by 
  t1.date_id, t1.customer;

Sample SQL Fiddle

答案 1 :(得分:1)

您可以采用的一种方法是使用一个子查询,该查询将所有订单汇总到当前订单。可能不是最快的方式,但它应该可以解决问题。

SELECT `Date_ID`, `Customer`, 
    (SELECT sum(b.`Order_Count`) 
    FROM tablename as b WHERE 
    b.`Date_ID` <= a.`Date_ID` AND
    a.`customer = b.`Customer`) 
FROM tablename as a

答案 2 :(得分:1)

如果性能存在问题,请考虑以下解决方案:

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

SELECT i,@i:=@i+i FROM ints, (SELECT @i:=0)n ORDER BY i;
+---+----------+
| i | @i:=@i+i |
+---+----------+
| 0 |        0 |
| 1 |        1 |
| 2 |        3 |
| 3 |        6 |
| 4 |       10 |
| 5 |       15 |
| 6 |       21 |
| 7 |       28 |
| 8 |       36 |
| 9 |       45 |
+---+----------+