0

我有一张付款请求表。

PaymentId (UNSIGNED INT AI)
ClientId (USINGNED INT)
Amount (FLOAT)
PayTo (DATE)

因为对于 PayTo,通常不超过 2-3 个不同的值(每个客户)我想创建列表 - 到目前为止应该支付多少钱。我是否正在寻找这样的查询:

SELECT PayTo, SUM(IF(PayTo <= PayTo, Amount, 0)) as AmountThisDate 
FROM Payments 
WHERE ClientId='%d' 
GROUP BY PayTo
ORDER BY PayTo DESC

但我百分百确定

PayTo <= PayTo

不会工作。

如果它是同一列,那么一次访问 GROUP BY Column 和 TABLE 列的正确方法是什么?

4

2 回答 2

1

听起来你想要一个累积的总和。这是使用相关子查询的方法:

SELECT p1.PayDate,
       (select sum(p2.amount)
        from Payments p2
        where p2.ClientId = p.ClientId and
              p2.PayDate <= p.PayDate
       ) as AmountThisDate
FROM Payments p1
WHERE p1.ClientId='%d' 
GROUP BY p1.PayDate 
ORDER BY p1.PayDate DESC;

通过在 上设置索引可以提高性能payments(ClientId, PayDate, Amount)

于 2013-07-23T13:56:39.300 回答
0
SELECT PayDate, SUM(IF(PayDate <= current_date(), Amount, 0)) as AmountThisDate 
FROM Payments 
WHERE ClientId='%d' 
GROUP BY PayDate 
ORDER BY PayDate DESC

这是你要找的吗?

于 2013-07-23T14:00:56.027 回答