Thursday, November 15, 2012

How to get total sum


PROBLEM

I have two tables.
Sales
------

ID Charge VAT
1 100 10
2 200 20


SaleProducts
------------

ID Product Auto SalesID
1 aa True 1
2 bb False 1
I want to get this
SaleOnProduct
-------------

ID Product Charge VAT Total TotalAmount
(All of total is plus)
1 aa 100 10 110 220
2 aa 100 10 110 220
How can I do this. Please help me.


SOLUTION

declare @Sales table (ID int, Charge int, VAT int)
declare @SaleProducts table (ID int, Product char(2), Auto bit, SalesID int)

insert into @Sales values
(1, 100, 10),
(2, 200, 20)

insert into @SaleProducts values
(1, 'aa', 1, 1),
(2, 'bb', 0, 1)

select
SP
.ID,
SP
.Product,
S
.Charge,
S
.VAT,
S
.Charge+S.VAT as Total,
sum
(S.Charge+S.VAT) over() as TotalAmount
from @Sales as S
inner join @SaleProducts as SP
on S.ID = SP.SalesID

No comments:

Post a Comment