我有这个sql数据库
我希望显示以下数据:
注意:
总销售额=总和(ProductsTbl.SalePrice * OrderDetailsTbl.SoldQuantity)
折扣=总和(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
答案 0 :(得分: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.SalePrice
和 d.SoldQuantity