我有两张桌子。
Sales
------
ID Charge VAT
1 100 10
2 200 20
SaleProducts
------------
ID Product Auto SalesID
1 aa True 1
2 bb False 1
我想得到这个
SaleOnProduct
-------------
ID Product Charge VAT Total TotalAmount(All of total is plus)
1 aa 100 10 110 220
2 aa 100 10 110 220
我该怎么做?请帮帮我。
答案 0 :(得分:2)
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
答案 1 :(得分:0)
为了从同一结果集中的两个表中获取数据,您需要进行连接。
由于您希望每个特定产品的所有销售((费用+增值税)* numberofSaleProductsRows)都有一个汇总行,您需要使用SUM聚合函数和GROUP BY子句。结果集中需要的所有列以及没有指定聚合的列都需要包含在GROUP BY列表中。
免责声明:未经测试的代码
SELECT ID, Product, Charge ,VAT, Charge + VAT as Total,
Sum(Charge + VAT) as TotalAmount
FROM Sales INNER JOIN SaleProducts
ON Sales.ID = SaleProducts.SalesID
GROUP BY ID, Product, Charge, VAT, Charge + VAT
答案 2 :(得分:0)
此查询执行以下任务:(我认为SQL Server 2005或更高版本,否则您需要通过临时表更改cte)
WITH ReportCte as(
SELECT b.Id IdSale,
a.Id IdProduct,
a.Product,
b.Charge,
b.VAT,
b.Charge+b.VAT Total
FROM [dbo].[SaleProducts] a left join
[dbo].[Sales] b on a.[SalesID] = b.ID)
SELECT a.IdProduct,
a.IdProduct,
a.Charge,
a.VAT,
a.Total,
b.TotalAmount
FROM ReportCte a left join
(select IdSale,SUM(Total) TotalAmount
from ReportCte group by IdSale) b on a.IdSale=b.IdSale
答案 3 :(得分:-1)
select *, (charge+VAT) as total, SUM(charge+VAT) as totalAmount
from sales
join saleproducts on sales.ID=saleproducts.salesID
group by sales.ID