如何统计每个日期的历史总数据,我的表是这样的:id      profit(利润)     month(月)    date(日)  1         180               2                 8  2         220               2                 10  3         98                2                 16  4         100               3                 2  5         600               4                 8假如2月10号,就统计180+220得出400, 3月2号就统计180+220+98+100得出598,请问各位大侠,如何用mysql语句一次性查出每个日期下的历史总利润,是历史总利润,也就是该日期前面的利润总和(比如2月16号,就统计2月8号--2月16号的利润总和;4月8号,就统计2月8号--4月8号的利润总和)?这个问题困扰了很久,求各位打救打救!!! 

解决方案 »

  1.   

    select a.*, 
    (select sum(b.profit) from table b where 30*b.month+b.date <= 30*a.month+a.data) 
    from table a 
      

  2.   

    上面写的应该可以的。数据量小,应该是运行挺快的。如果数据量大,建议修改为 join的方式
      

  3.   

    不过话说回来,为什么month 和date列,要分开存储呢? 这个真奇怪。这样会导致就算有索引,也用不上的。
      

  4.   

    select a.id,a.profit,a.month,a.date,
    (select sum(profit) from 我的表 where `month`*100+`date`<=a.`month`*100+a.`date`) as 利润总和
    from 我的表 a
      

  5.   

    如果我的表时间用一个字段装起来呢?
    id     u_id       profit(利润)     total_time(时间戳)  1       2            180              1391817600                            (2014-02-08)  2       2             220             1391990400                             (2014-02-10)   3       5             98               1392508800                              (2014-02-16)  4        7            100             1393718400                               (2014-03-02)  5         2            600              1396915200                              (2014-04-08)sql语句该怎么改?? 还有如果要查u_id为 2 的历史总利润,sql语句又该怎么写?
      

  6.   

    第一个
    select a.*, 
    (select sum(b.profit) from table b where b.total_time < a.total_time) 
    from table a  第二个
    select sum(profit) from table where u_id = 2 
      

  7.   

    第二个我是查u_id为2的每个日期的历史总利润,表里总共有3个u_id为2的,sql怎么写???