0

我有这个 sql 数据库

在此处输入图像描述

我想显示我的数据,如下所示:

在此处输入图像描述

笔记:

总销售额 = Sum(ProductsTbl.SalePrice * OrderDetailsTbl.SoldQuantity)

折扣 = Sum(ProductsTbl.SalePrice * OrderDetailsTbl.SoldQuantity) * DiscountRatesTbl.DiscountRate/100

已付 = SUM(isnull(CashMovementTbl.CashMovementValue,00.00)

那么如何在 SQL Server 中进行查询以显示这样的数据。

谢谢你的帮助。

我尝试了此查询,但未能获得折扣:

SELECT  c.CustName as 'Customer' ,

Total Sales= ( SELECT SUM(p.SalePrice * d.SoldQuantity) FROM OrderDetailsTbl d 
INNER JOIN  OrdersTbl o ON d.orderID = o.orderID INNER JOIN  ProductsTbl p ON p.ProductID = d.ProductID
WHERE o.CustomerID = c.CustomerID ) ,

Discounts= (Select isnull(sum(p.SalePrice * d.SoldQuantity)* dr.DiscountRate/100),00.00 FROM OrderDetailsTbl d 
INNER JOIN  OrdersTbl o ON d.orderID = o.orderID INNER JOIN  ProductsTbl p ON p.ProductID = 
d.ProductID inner join DiscountRatesTbl dr on dr.orderID = o.orderID WHERE o.CustomerID = c.CustomerID ) ,

Payed=  ( SELECT  SUM(isnull(cm.CashMovementValue,00.00)) FROM CashMovementTbl cm
INNER JOIN OrdersTbl o  ON o.orderID = cm.orderID WHERE  o.CustomerID = c.CustomerID)

FROM    CustomersTbl c
where ( SELECT SUM(p.SalePrice * d.SoldQuantity) FROM OrderDetailsTbl d 
INNER JOIN  OrdersTbl o ON d.orderID = o.orderID INNER JOIN  ProductsTbl p ON p.ProductID = 
d.ProductID WHERE o.CustomerID = c.CustomerID ) is not null 
order by c.CustName
4

1 回答 1

1

这不是查询编写的最佳方式...

但是用以下内容替换您的折扣计算查询部分:

Discounts= (Select isnull(SUM(p.SalePrice * d.SoldQuantity* dr.DiscountRate/100),00.00) FROM OrderDetailsTbl d 
INNER JOIN  OrdersTbl o ON d.orderID = o.orderID INNER JOIN  ProductsTbl p ON p.ProductID = 
d.ProductID inner join DiscountRatesTbl dr on dr.orderID = o.orderID WHERE o.CustomerID = c.CustomerID ) ,

这将起作用。

简单地说,SUM必须包括所有乘数,而不是简单的p.SalePriced.SoldQuantity

于 2013-10-31T16:34:55.533 回答