【问题标题】:How can I add subtotal to table in MySQL?如何在 MySQL 中将小计添加到表中?
【发布时间】:2015-11-06 15:10:08
【问题描述】:

假设我的表格如下所示:

id    count    sub_total
1     10       NULL
2     15       NULL
3     10       NULL
4     25       NULL

如何更新此表以如下所示?

id    count    sub_total
1     10       10
2     15       25
3     10       35
4     25       60 

我可以在应用层轻松做到这一点。但我想学习如何在 MySQL 中做到这一点。我一直在尝试使用SUM(CASE WHEN... 和其他分组进行很多变化,但无济于事。

【问题讨论】:

    标签: mysql sum case


    【解决方案1】:

    如果您的 id 字段是连续的并且不断增长,那么关联子查询是一种方法:

    select *, (select sum(count) from t where t.id <= t1.id) 
    from t t1
    

    或作为连接:

    select t1.id, t1.count, sum(t2.count)
    from t t1
    join t t2 on t2.id <= t1.id
    group by t1.id, t1.count
    order by t1.id
    

    更新您的表(假设列 sub_total 已经存在):

    update t 
    join (
      select t1.id, sum(t2.count) st
      from t t1
      join t t2 on t2.id <= t1.id
      group by t1.id
    ) t3 on t.id = t3.id
    set t.sub_total = t3.st;
    

    Sample SQL Fiddle 显示更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多