SQL Server calculate running total value with query -


I use SQL Server 2012 and there is a table like the following:

  DE TALLET @ TABLE (value INT, [type] CHAR (1), quantity INT, value money, unit price value (value / quantity) @ value (1, 'i', 30, 1500), (2, 'o' 5, null), (3, 'o', 20, faucet), (4, 'o', 2, null), (5, 'i', 10, 2500), (6, 'i', 8, 1000), (7, 'o', 3, null), (8, 'o', 10, ft), (9, 'i', 12, 3600)  

In the table, I have the unit value for the record type of 'I' and 'O' with ('I' and 'O') with the price column Use R's record to calculate the last 'I' type record value I RunningTotalPrice (the sum of the quantities * unit part of each row).

The following code is calculated by running the Calcutta: < Pre> SELECT *, SUM (in case [type] = 'I' then the volume is calculated on the ELSE -Quantity END (ID as per order) AS QuantityRunningTotal @t

and The result of this query is:

  ID type volume price unit per quantity running total 1 I 30 1500/00 50/00 30 2 o5 Ell faucet 25 3 o 20 faucet faucet 5 4 o 2 null faucet 3 5 ii 10 2500/00 250/00 13 6 I 8 1000/00 125/00 21 7 O 3 Nail nail 18 8 o 10 Faucet Faucet 8 9I12 3600/00 300/00 20  

I have to lower the result

ID type Quantity quantity Unit per quinity rowing Total value Running plus 1 I 30 1500 / 00 50/00 30 1500/00 1500/00 2 o 5 faucet 50/00 25 250/00 1250/00 3 O 20 Faucet 50/00 5 1000/00 250/00 4 O 2 Faucet 50/00 3 100 / 00 150/00 5 I 10 250 0/00 250/00 13 2500/00 2650/00 6 I 8 1000/00 125/00 21 1000/00 3650/00 7 O 3 NULL 125/00 18 375/00 3275 / 00 8 O 10 Null 125/00 8 1250/00 2025/00 9I 12 3600/00 300/00 20 3600/00 5625/00

Before Records UnitPris column of value tap with existing unitprice. And calculate the value (quantity * unitpris) and total cost of calculation.

Unfortunately LEAD and LAG functions The last no NULL can not be used in the value, so you will need to use the OUTER APPLY to use the previous UnitPrice where type is 'o':

  SELECT t.ID, t [Type], t. Quantity, t. Price, T. UnitPrice, SUM (Case when T. [Type] = 'I' then T. volume ELES-T Quantity END) Over (Order by TIID) AS QuantitaringTotal, case when T. [Type] = 'I' then T. Price ELSE t.Quantity * p.UnitPrice END as Price2, SUM (Case when T. [Type] = 'I' then T. value ELSE -t.Quantity * p.UnitPrice END) (Order by T) AS Quantity Ringtones @ A.S. Apply from T Out (Select Top 1 T2. ATS T2 WHERE T 2.ID & lt; t.ID and t2.UnitPrice t2.id from Unit Paper is not Task Order by DESC) P;  

Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -