Question

I'm trying to add a calculated row to a table using the Insert Into. So roughly i'm trying to add and split the following:

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

So that I get:

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

As you can see, I added all of Name 2 and then divided into two rows: one that has 42% of the total, and one for 58% of the total.

Adding the calculated variable is pretty straightforward:

First I declare my variable which is

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;

Then I add:

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

However, now i'm stuck with a new row with 42% of the total, but can't seem to change the remaining rows to reflect only 58% of their original values, even if I run an update BEFORE I insert the new row (I'm not sure how it works but it seems as though the variable does not "store" the number for another query).

Any ideas on how I can achieve this? Thanks in advance!

Was it helpful?

Solution

I think the easiest thing would be to use a second variable and compute its value before doing your inserts.

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top