MySQL,比较后递归添加两列
这是我的表格数据:MySQL,比较后递归添加两列,mysql,sql,mysql-workbench,Mysql,Sql,Mysql Workbench,这是我的表格数据: 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
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,并且如果最终值为max,则应将其应用于具有相同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 t.*, max(column1) over (partition by id) as column2
from t;
MySQL不支持窗口函数。您可以通过以下方式使用联接和组来执行此操作:
您需要最大窗口功能:
select t.*, max(column1) over (partition by id) as column2
from t;
MySQL不支持窗口函数。您可以通过以下方式使用联接和组来执行此操作:
试试这个:
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的演示:试试这个:
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的演示:我删除了无关的数据库标记。请为您真正使用的数据库添加标记。我删除了无关的数据库标记。请为您真正使用的数据库添加标记。感谢快速响应@10086,但请查看id=2。column2值为0.3333,但应为0.1429+0.2500=0.39。有什么建议吗?非常感谢:感谢快速响应@10086,但请查看id=2。column2值为0.3333,但应为0.1429+0.2500=0.39有什么建议吗?非常感谢:不,事实上这不是一个简单的最大值函数,它是一个运行总和well@Nomanuddin . . . 在我看来更像一个马克斯。我承认id=2不太合适,但id 1、3和4确实合适。实际上,如果id 1、3、4也有id=2这样的数据类型,那么max将不起作用。谢谢@Gordon linoffnops实际上这不是一个简单的max函数,它是一个连续的求和函数well@Nomanuddin . . . 在我看来更像一个马克斯。我承认id=2不太合适,但id 1、3和4确实合适。实际上,如果id 1、3、4也有id=2这样的数据类型,那么max将不起作用。谢谢你@Gordon Linoff