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 The following code is calculated by running the Calcutta: < Pre> and The result of this query is: I have to lower the result ('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).
SELECT *, SUM (in case [type] = 'I' then the volume is calculated on the ELSE -Quantity END (ID as per order) AS QuantityRunningTotal @t
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
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
Post a Comment