gpt4 book ai didi

MySQL,比较后递归添加两列

转载 作者:行者123 更新时间:2023-11-29 04:37:13 24 4
gpt4 key购买 nike

这是我的表格数据:

   ID   val   Coulmn1  Column2
1 1 0.4000 0
1 10 0.1250 0
1 18 0.1429 0
1 26 0.2500 0
2 13 0.0000 0
2 21 0.1429 0
2 29 0.2500 0
2 34 0.3333 0
3 6 0.3333 0
3 7 0.20 0
3 14 0.2500 0
3 22 0.1429 0
3 33 0.2500 0
4 8 0.2000 0
4 15 0.1250 0
4 23 0.1429 0
4 31 0.0000 0

如果同一行中的 column1 大于 column2,我想添加到列中,并且如果最终值为最大值,则应将其应用于同一 ID 的所有行。

我有以下场景。

if (Column1 > Column1 ) 
then (Column1 + Column1 )
else (Column1 )

输出可以是:

       ID   val   Coulmn1    Column2
1 1 0.4000 0.4000
1 10 0.1250 0.4000
1 18 0.1429 0.4000
1 26 0.2500 0.4000
2 13 0.0000 0.39285
2 21 0.1429 0.39285
2 29 0.2500 0.39285
2 34 0.3333 0.39285
3 6 0.3333 0.3333
3 7 0.20 0.3333
3 14 0.2500 0.3333
3 22 0.1429 0.3333
3 33 0.2500 0.3333
4 8 0.2000 0.2
4 15 0.1250 0.2
4 23 0.1429 0.2
4 31 0.0000 0.2

任何支持链接或解决方案提前致谢

最佳答案

试试这个:

select
t1.id, t1.val, t1.column1,
t2.col as column2
from yourtable t1
join (
select
max(tmp.col) as col,
id
from (
select
yourtable.*,
@col := case when @grp = id then
case when @col < column1 then @col + column1 else @col end
else column1 end as col,
@grp := id
from yourtable
cross join (select @col := 0, @grp := null) t
order by id, val
) tmp
group by id
) t2 on t1.id = t2.id

这几乎适用于所有数据库。

这里是 mysql 的演示:SQLFiddle Demo

关于MySQL,比较后递归添加两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38449163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com