Click here to Skip to main content
16,015,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have this sql database

http://i.stack.imgur.com/NCL4T.jpg[^]

And I want to show my data such as following:

http://i.stack.imgur.com/KX6KS.jpg[^]

Note:

Total sales = Sum(ProductsTbl.SalePrice * OrderDetailsTbl.SoldQuantity)

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

Payed = SUM(isnull(CashMovementTbl.CashMovementValue,00.00)

I tried this query but failed to got Discounts:

SQL
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


So how can I do a query in SQL Server to show data like that.

Thanks for any help.
Posted
Updated 31-Oct-13 6:20am
v3
Comments
ZurdoDev 31-Oct-13 12:42pm    
What part are you stuck on?
RedDk 31-Oct-13 13:46pm    
Not going to i.stack.imgr.com for anything

1 solution

Your bug is in
Select isnull(sum(p.SalePrice * d.SoldQuantity)* dr.DiscountRate/100),00.00


The closing bracket on isnull is not including the default value for when the discount is null.

This should probably be something like
Select (sum(p.SalePrice * d.SoldQuantity)* isnull(dr.DiscountRate/100, 0))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900