mysql - 如何将单笔订单表转化成累加订单表
PHPz
PHPz 2017-04-17 15:34:01
0
6
492

有表1如下

id name money time
1 mike 6 2016-09-01
2 mike 648 2016-09-01
3 leo 488 2016-09-02
4 mike 6 2016-09-03

如何获得以下表2内容

id name amount time
1 mike 6 2016-09-01
2 mike 654 2016-09-01
3 leo 488 2016-09-02
4 mike 660 2016-09-03
PHPz
PHPz

学习是最好的投资!

reply all(6)
伊谢尔伦

At present, I have also thought of a way. I don’t know if there is a better way to compare and learn from each other

select id,name,(select sum(money) from test b where b.name = a.name and b.time <= a.time) as amount,time from test a
巴扎黑

Thank you for the invitation, try this~

    SELECT a.id,a.name,SUM(lt.money)  as amount
    FROM test a JOIN test lt 
    ON a.time >= lt.time//如果时间是递增的可以使用id判断
    GROUP BY a.money
    ORDER BY id
迷茫

Thanks for the invitation. Do you want to accumulate the amount field? Isn’t it possible to use user IDs for conditional accumulation?

PHPzhong

You can take a look at the union keyword in sql

大家讲道理

I feel that sql is not good at doing this kind of thing, and it would be better to put it in the code.

If there is one record per user, then group by + sum is enough.

大家讲道理

This is a stored procedure

DELIMITER $$
DROP PROCEDURE IF EXISTS `get_totaltab`$$
CREATE PROCEDURE `get_totaltab`()
BEGIN
  declare i int default 1;
  while i < 5
  do
    INSERT INTO  book_copy SELECT max(id),name,sum(money),max(time) from book where name=(SELECT name FROM book where id=i) and id<=i;
    set i = i + 1;
  end while;
END$$
DELIMITER ;
CALL get_totaltab()

This is the result, as shown below

1    mike    6      2016-09-01
2    mike    654    2016-09-01
3    leo     488    2016-09-02
4    mike    660    2016-09-03
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!