2013-10-31 66 views
0

我有這樣的SQL數據庫如何在sql server中獲得此報告的查詢?

enter image description here

而且我想告訴我的數據,如下列:

enter image description here

注:

總銷售額= 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 
+0

你嘗試過什麼不是簡單的乘法? –

+0

@SuperHornet是的我試圖添加我的問題,但它失敗:( –

+0

只是愚蠢的事情:有一個錯字:dr..orderID不應該dr.orderID –

回答

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

+0

非常感謝@Sandr,它現在工作正常 –