我有以下数据库结构:
[Order]
OrderId
Total
[Payment]
OrderId
Amount
每个订单都可以有X个付款行。我想只得到所有付款总和的订单清单。比订单总数。
我有以下SQL,但我将返回已支付和未支付的所有订单。
SELECT o.OrderId,
o.UserId,
o.Total,
o.DateCreated,
COALESCE(SUM(p.Amount),0) AS Paid
FROM [Order] o
LEFT JOIN Payment p ON p.OrderId = o.OrderId
GROUP BY o.OrderId, o.Total, o.UserId, o.DateCreated
我试图添加Where(付费< o.Total)但是它不起作用,任何想法? BTM我正在使用SQL CE 3.5
答案 0 :(得分:4)
您正在寻找的是HAVING子句。
而不是“Where(COALESCE(SUM(p.Amount),0)&lt; o.Total)”,而不是“HAVING(COALESCE(SUM(p.Amount),0)&lt; o.Total)”< / p>
答案 1 :(得分:0)
Select Order.* From Order
Left Join
(Select OrderID, Sum(Amount) As t From Payment Group By OrderID) As s On s.OrderID = Oder.OrderID
Where IsNULL(s.t,0) < Order.Total