【问题标题】:SQL join with comparison operator problem带有比较运算符问题的 SQL 连接
【发布时间】:2021-12-09 04:49:30
【问题描述】:

我有一个非常棘手的 SQL 问题,也许是我遇到过的最棘手的问题 假设我在下面有一张桌子

调用 table_1

Date spend
Oct. 20 50
Oct. 19 40
Oct. 18 50
Oct. 17 60
Oct. 16 50

现在我需要另一个表格来汇总我之前的所有支出,并包括每个日期。喜欢展示我迄今为止在每个日期花费的每一笔钱。

对于每个日期。

下面是我要计算的表

调用 table_2

Date spent
Oct. 20 250 ( sum of all the spend before and includes Oct.20)
Oct. 19 200 ( sum of all the spend before and includes Oct.19)
Oct. 18 160 ( sum of all the spend before and includes Oct.18)
Oct. 17 110 ( sum of all the spend before and includes Oct.17)
Oct. 16 50 ( sum of all the spend before and includes Oct.16)

我已经尝试在 date_1

不工作。

有人可以给我一个提示吗?

【问题讨论】:

    标签: mysql sql left-join


    【解决方案1】:

    您想要一个运行总计。你可以通过windw函数SUM OVER得到这个。

    select date, sum(spend) over(order by date) as sum_spent 
    from mytable
    order by date desc;
    

    如果您不得不使用不支持窗口函数的旧 MySQL 版本,这里有一个老式的替代方案:

    select 
      date, 
      (select sum(spend) from mytable t2 where t2.date <= t.date) as sum_spent 
    from mytable t
    order by date desc;
    

    【讨论】:

      【解决方案2】:

      补充 Thorsten Kettner 的回答,LEFT JOIN 你已经尝试过也有效

      SELECT a.date, SUM(b.spend)
      FROM table_1 a
      LEFT JOIN table_1 b ON a.date >= b.date
      GROUP BY a.date
      

      【讨论】:

        猜你喜欢
        • 2021-06-10
        • 2011-06-20
        • 1970-01-01
        • 2015-08-03
        • 2010-12-02
        • 1970-01-01
        • 1970-01-01
        • 2022-10-15
        • 1970-01-01
        相关资源
        最近更新 更多