我的数据库中有这些表:
*custmrsTble: (custID: PK,Int) - (Name: varchar(20))
=============
custID Name
________________
1 Sam
2 Tom
ProductsTble: (prodID: PK,Int) - (prodName: varchar(20)) - (soldPrice: money)
===========
prodID prodName soldPrice
____________________________
1 Biscuits 20
2 Butter 30
3 Milk 10
OrdersTbl: (orderID: PK,Int) - (orderDate: smallDateTime) - (custID: FK,Int)
==========
orderID orderDate custID
____________________________
1 2013/4/2 1
2 2013/4/2 2
3 2013/4/3 1
OrderDetails: (orderDetailsID : PK,Int)- (orderID: FK,Int) - (prodID: FK,Int) - (qntty: int)
=============
orderDetailsID orderID prodID qntty
_______________________________________
1 1 1 2
2 1 2 1
3 1 3 2
4 2 1 5
5 3 1 1
CashMoventsTble: (cashID : PK,Int)- (orderID: FK,Int) - (cashDate : smallDateTime) - (cashValue money)
================
cashID orderID cashDate cashValue
_____________________________________
1 1 2013/4/2 30
2 2 2013/4/2 100
3 1 2013/4/5 20
4
所以,我想查询哪些会返回客户状态:
Name TotalPurchase TotalPayments
_______________________________________
Sam 110 50
Tom 100 100
TotalPurchase = sum(qntty)* soldPrice ---->全部为每位顾客购买 TotalPayments = sum(cashValue)----->每个客户的所有付款
但不确定该怎么做。所以请帮助我实现这一目标。 感谢。
答案 0 :(得分:0)
SELECT c.Name
,TotalPurchase = (
SELECT SUM(p.soldPrice * d.qntty)
FROM OrderDetails d
INNER JOIN OrdersTbl o
ON d.orderID = o.orderID
INNER JOIN ProductsTbl p
ON p.prodID = d.prodID
WHERE o.custID = c.custID )
,TotalPayments = (
SELECT SUM(cm.cashValue)
FROM CashMoventsTble cm
INNER JOIN OrdersTbl o
ON o.orderID = cm.orderID
WHERE o.custID = c.custID)
FROM custmrsTble c