按虚拟列过滤?

时间:2010-12-21 21:50:35

标签: sql sql-server-ce

我有以下数据库结构:

[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

2 个答案:

答案 0 :(得分:4)

您正在寻找的是HAVING子句。

而不是“Where(COALESCE(SUM(p.Amount),0)&lt; o.Total)”,而不是“HAVING(COALESCE(SUM(p.Amount),0)&lt; o.Total)”< / p>

查看MSDN Reference on HAVING

答案 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