2011-06-17 31 views
3

我對這個網站很陌生,對任何事情都很陌生。 我不知道要問的方式。所以我之前問過1個問題(我把它作爲答案發布),並且我再次發佈瞭解決方案。你的所有想法都幫助我解決了這個問題。使用CTE相互計算多個列

現在這裏出現了新的問題。

我想建立彼此計算的列。 (對不起,我英文) 例子:

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 

那麼複雜??? :-(

上一個問題是計算Column3的新計算列爲Column2,但現在它必須與剛計算的Column2以及Column3的前一個記錄一起更新如果您想查看以前的帖子,here it is

我期待着任何答案,這將不勝感激。謝謝你在前進

多克


首先,感謝您爲您的所有想法的傢伙。

我再次解釋,因爲它不清楚。

這是我以前的遞歸CTE代碼。它的工作原理類似於:1,用cteCalculation中的當前列(c.Column2)的先前記錄計算column2,然後用cteCalculation中的僅計算column2計算cte2中的新列3。

/從以前的交複製/

;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來獲得新的第二列數據。希望你能得到它。

多克

+0

只是好奇地實現這一目標。這與什麼問題有關? – 2011-06-17 13:54:07

+0

請確認你的表是否只有`Column1`或者每個列都有問題。如果它確實有三列,那麼解決方案是微不足道的(請參閱@BonyT發佈的答案),並且不需要使用CTE。 – Yuck 2011-06-17 13:57:08

+0

表可以在計算之前包含所有這些列。但是沒有CTE我就無法解決它,對我感到羞恥。我會盡力找到,謝謝 – Dok 2011-06-18 02:57:51

回答

0

你需要使用Recursive CTE因爲後續列的值取決於先前的結果。

也是這樣做的。你的第一個查詢只返回Column1的正確值。您的下一個(遞歸CTE)查詢將爲Column2添加結果,依此類推。

0

好吧我假設你正在插入到第1列這裏的各種值。

本質COL2總是=新COL1值+舊COL2值+舊第3欄第值 COL3 =新COL2值+舊COL3值 所以COL3 =(新COL1值+舊COL2值+舊COL 3值)+老col3值

所以INSTEAD OF插入觸發器可能是最簡單的實現方法。

CREATE TRIGGER tr_xxxxx ON Tablename 

INSTEAD OF INSERT 

AS 

INSERT INTO Tablename (Column1, Column2, Column3) 
SELECT ins.col1, ins.col1+t.col2+t.col3, ins.col1+t.col2+t.col3+t.col3 
FROM Tablename t INNER JOIN Inserted ins on t.Id = ins.Id 

觸發器既可以訪問Tablename t中的現有(舊)值,也可以插入新值(Inserted.col1)。

1

這是一個例子,如何使用遞歸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