如何创建基于复杂规则的sql?

cpjpxq1n  于 2021-06-17  发布在  Mysql
关注(0)|答案(4)|浏览(279)

我有3列(id,date,amount)并试图计算第4列(calculated\u列)。
如何创建sql查询以执行以下操作:
需要计算的方法是查看id(例如,1)并查看该月的所有相同id(例如,对于第一次发生-9月1日,应将其计算为5,对于第二次发生-应为5+6=11->从该月初开始的所有金额,包括该金额)。
然后在下个月(10月)-它将找到id=1的第一个匹配项,并将3存储在计算列中,对于10月的第二个id=1,它将从该月初开始对同一id进行求和(3+2=5)

0x6upsns

0x6upsns1#

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

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 以适合您的数据)

mm5n2pyu

mm5n2pyu2#

以下是针对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
mitkmikd

mitkmikd3#

在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 就是将值放在结果集的相应行上。如果月份中的所有行都具有相同的值,则代码会更简单。

wfypjpf4

wfypjpf44#

如果您的版本支持窗口功能(如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
;

相关问题