0

我有 3 列(id、date、amount)并试图计算第 4 列(calculated_column)。

如何创建 SQL 查询以执行以下操作:

需要计算的方式是查看 ID(例如 1)并查看该月的所有相同 ID(例如,对于第一次出现 - 1-Sep,它应该计算为 5,对于第二次出现 - 这将是 5+6 =11 -> 从该月开始的所有金额,包括该金额)。

然后在下个月(10 月) - 它会发现 id=1 的第一次出现并将 3 存储在计算的_column 中,对于 10 月的 id=1 的第二次出现,它将从该月初开始对相同的 id 进行求和(3+ 2=5)

在此处输入图像描述

4

4 回答 4

1

假设我理解正确,我会建议一个相关的子查询,例如:

select t.*, 
(
    select sum(u.amount) from table1 u  
    where 
        u.id = t.id and
        date_format(u.date, '%Y-%m') = date_format(t.date, '%Y-%m') and u.date <= t.date
) as calculated_column
from table1 t

(更改表名table1以适合您的数据)

于 2018-11-28T22:39:03.257 回答
1

在 Oracle 和 MySQL 8+ 中,您可以使用窗口函数。相应的日期算术各不相同,但想法如下:

select t.*,
       (case when date = max(date) over (partition by to_char(date, 'YYYY-MM') and
                  id = 1
             then sum(amount) over (partition by to_char(date, 'YYYY-MM')
        end) as calculated_column
from t;

外部case只是将值放在结果集的适当行上。如果月份中的所有行都具有相同的值,则代码会更简单。

于 2018-11-28T22:39:17.307 回答
1

这是oracle的解决方案。由于你没有给表名我将其命名为my_table,将其更改为真实名称

select
    t1.id, 
    t1.date,
    t1.amount,
    decode(t1.id, 1, sum(nvl(t2.amount, 0)), null) calculated_column
from my_table1 t1
left join my_table t2 
    on trunc(t2.date, 'month') = trunc(t1.date, 'month')
    and t1.id = 1
group by t1.id, t1.date, t1.amount
于 2018-11-28T22:49:08.707 回答
1

如果您的版本支持窗口功能(例如 MySQL 8 以上)

# MySQL 8+
select 
       t.*
     , sum(amount) over (partition by id, date_format(date, '%Y-%m-01') order by date) as calculated_column
from t
;

-- Oracle
select 
       t.*
     , sum(amount) over (partition by id, trunc(date, 'MM') order by date) as calculated_column
from t
;
于 2018-11-28T22:50:45.930 回答