2013-12-19 57 views
1

我正在嘗試使用「插入」將計算行添加到表中。 所以大概我試圖添加和拆分以下內容:在sql中添加一行變量

 [RFC]  [Tons] 
[1] NAME 1  30 
[2] NAME 2  50 
[3] NAME 2  30 
[4] NAME 2  20 

所以,我得到:

 [RFC]  [Tons] 
[1] NAME 1  30 
[2] NAME 2  42 
[3] NAME 2  58 

正如你所看到的,我添加的所有名稱2,然後分成兩排:佔總數的42%,一個佔總數的58%。

將計算出來的變量是非常簡單的:

首先我聲明我的變量,它是

DECLARE @TonsE int; 
SET @TonsE = CASE 
WHEN 
(SELECT SUM(mkt_impotemporal.Tons)*0.42 FROM mkt_impotemporal where RFC='EHP040219KX0' GROUP BY RFC) is null THEN 0 
ELSE 
(SELECT SUM(mkt_impotemporal.Tons)*0.42 FROM mkt_impotemporal where RFC='EHP040219KX0' GROUP BY RFC) 
END; 

然後我補充一下:

INSERT INTO mkt_impotemporal 
VALUES 
('EHP040219KX0', 
@TonsE) 

然而,現在我卡住了新行佔總數的42%,但似乎無法更改其餘行以僅反映其原始值的58%,即使我在插入新行之前運行更新(我不是sur e它是如何工作的,但似乎變量不會「存儲」另一個查詢的數字)。

關於我如何實現這一點的任何想法?提前致謝!

+0

你正在使用什麼數據庫系統? –

+0

@AlexanderFedorenko SQL 2012. – eflores89

回答

1

我認爲最簡單的事情是在插入之前使用第二個變量並計算它的值。

DECLARE @TonsE int; 
SET @TonsE = CASE 
WHEN 
(SELECT SUM(mkt_impotemporal.Tons)*0.42 FROM mkt_impotemporal where RFC='EHP040219KX0' GROUP BY RFC) is null THEN 0 
ELSE 
(SELECT SUM(mkt_impotemporal.Tons)*0.42 FROM mkt_impotemporal where RFC='EHP040219KX0' GROUP BY RFC) 
END; 

DECLARE @TonsE2 int; 
SET @TonsE = CASE 
WHEN 
(SELECT SUM(mkt_impotemporal.Tons)*0.58 FROM mkt_impotemporal where RFC='EHP040219KX0' GROUP BY RFC) is null THEN 0 
ELSE 
(SELECT SUM(mkt_impotemporal.Tons)*0.58 FROM mkt_impotemporal where RFC='EHP040219KX0' GROUP BY RFC) 
END; 

--DELETE FROM mkt_impotemporal WHERE RFC = 'EHP040219KX0' 

INSERT INTO mkt_impotemporal 
VALUES 
('EHP040219KX0', 
@TonsE); 

INSERT INTO mkt_impotemporal 
VALUES 
('EHP040219KX0', 
@TonsE2) 
+0

我實際上已經創建了另一個表來存儲數字,再次擦除和複製,但是您的解決方案更加優雅/高效。謝謝!! – eflores89