gpt4 book ai didi

sql - 使用CTE相互计算多列

转载 作者:行者123 更新时间:2023-12-04 20:56:13 25 4
gpt4 key购买 nike

我对这个网站以及所有事物都很陌生。
而且我不知道问的方式。因此,我之前问了一个问题(我将其发布为答案),然后像我一样再次发布了解决方案。您的所有想法都帮助我解决了这个问题。

现在,这里出现了新问题。

我想建立相互计算的列。 (对不起我的英语不好)
例:

Id   Column1    Column2                                                           Column3
1 5 5 => Same as Column1 5 => Same as Column2
2 2 12 => column1 current + column2.prev + column3.previous = 2+5+5 17 => column2.current + column3.prev = 12+5
3 3 32 => 3+12+17 49 => 32+17


更简单的查看方式:

Id   Column1    Column2                  Column3
1 5 5 => Same as Column1 5 => Same as Column2
2 2 12 => 2+5+5 17 => 12+5
3 3 32 => 3+12+17 49 => 32+17


太复杂了??? :-(

先前的问题是使用新计算的列作为Column2计算Column3。但是现在,必须使用刚刚计算的Column2和以前的Column3记录对其进行续订。如果要查看上一篇文章, here it is

我期待任何答案,我们将不胜感激。先感谢您

k



首先,谢谢你们的所有想法。

我再次解释,因为不清楚。

这是我以前的递归CTE代码。它的工作方式类似于1,使用cteCalculation中的当前列(c.Column2)的先前记录来计算column2,然后使用刚刚从cteCalculation计算出的column2来计算cte2中的新column3。

/摘自先前的帖子/

;with cteCalculation as (
select t.Id, t.Column1, t.Column1 as Column2
from table_1 t
where t.Id = 1
union all
select t.Id, t.Column1, (t.Column1 + c.Column2) as Column2
from table_1 t
inner join cteCalculation c
on t.Id-1 = c.id
),
cte2 as(
select t.Id, t.Column1 as Column3
from table_1 t
where t.Id = 1
union all
select t.Id, (select column2+1 from cteCalculation c where c.id = t.id) as Column3
from table_1 t
inner join cte2 c2
on t.Id-1 = c2.id
)

select c.Id, c.Column1, c.Column2, c2.column3
from cteCalculation c
inner join cte2 c2 on c.id = c2. id


现在,我想扩展它,就像使用彼此的数据计算2列一样。意思是,使用2nd计算第三,然后使用3rd获得新的第二列数据。希望你能得到它。

k

最佳答案

这是一个示例,如何使用递归CTE实现

create table #tmp (id int identity (1,1), Column1 int)
insert into #tmp values(5)
insert into #tmp values(2)
insert into #tmp values(3);

with counter as
(
SELECT top 1 id, Column1, Column1 as Column2, Column1 as Column3 from #tmp
UNION ALL
SELECT t.id, t.Column1,
t.Column1 + counter.Column2 + counter.Column3,
(t.Column1 + counter.Column2 + counter.Column3) + counter.Column3 FROM counter
INNER JOIN #tmp t ON t.id = counter.id + 1
)

select * from counter

关于sql - 使用CTE相互计算多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6385812/

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