想要实现带条件的聚合方式, 有办法实现吗?

Viewed 51

比如有这样的一个表, 聚合字段希望其能在某个区间做 min 聚合, 超出区间则用 replace

create table if not exists t_temp (
    a int not null,
    b datev2 if(datediff(new, old) <= 3, min, replace) -- 这里的 new 表示要写入的数据值, old 表示已有的值
)
aggregate key(a)
distributed by hash(a) buckets auto
properties (
    "replication_allocation" = "tag.location.default: 1"
);


insert into t_temp values(1, '2024-01-01'); -- 写入后 b 的值预期是 2024-01-01
insert into t_temp values(1, '2024-01-04'); -- 写入后 b 的值预期是 2024-01-01, 新旧时间的差异在 3 以内则用 min
insert into t_temp values(1, '2024-01-05'); -- 写入后 b 的值预期是 2024-01-05, 新旧时间的差异超过了 3 则用 replace

同样的功能, 用 mysql 可以通过下面的方式来完成

drop table if exists t_temp;
create table t_temp (
    a int primary key,
    b date
);


insert into t_temp values(1, '2024-01-01')
on duplicate key update b =
    if(datediff(values(b), t_temp.b) <= 3, if(values(b) < t_temp.b, values(b), t_temp.b), values(b));
-- 写入后 b 的值是 2024-01-01
select * from t_temp;

insert into t_temp values(1, '2024-01-04')
on duplicate key update b =
    if(datediff(values(b), t_temp.b) <= 3, if(values(b) < t_temp.b, values(b), t_temp.b), values(b));
-- 写入后 b 的值是 2024-01-01, 新旧时间的差异在 3 以内则用 min
select * from t_temp;

insert into t_temp values(1, '2024-01-05')
on duplicate key update b =
    if(datediff(values(b), t_temp.b) <= 3, if(values(b) < t_temp.b, values(b), t_temp.b), values(b));
-- 写入后 b 的值是 2024-01-05, 新旧时间的差异超过了 3 则用 replace
select * from t_temp;


drop table t_temp;

对应的 Q&A 在 github 也是我提的: https://github.com/apache/doris/discussions/45302

1 Answers

Doris建表不支持你这种形式的,所以你可以通过update的方式来实现。即写一个udf,在update的时候,使用就可以了。例如
update table set b=udf where a =xxx;