我有一张包含付款请求的表格。
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列的正确方法是什么?
答案 0 :(得分: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)
上建立索引,可以提高效果。
答案 1 :(得分:0)
SELECT PayDate, SUM(IF(PayDate <= current_date(), Amount, 0)) as AmountThisDate
FROM Payments
WHERE ClientId='%d'
GROUP BY PayDate
ORDER BY PayDate DESC
这是你在找什么?