[英]Finding a date from a SUM
我很难找到我的客户在什么日期达到多少收入的某个门槛。
customer_id | Amount | created_at
---------------------------
1134 | 10 | 01.01.2010
1134 | 15 | 02.01.2010
1134 | 5 | 03.24.2010
1235 | 10 | 01.03.2010
1235 | 15 | 01.03.2010
1235 | 30 | 01.03.2010
1756 | 50 | 01.05.2010
1756 | 100 | 01.25.2010
为了确定他们赚了多少,我运行了一个简单的查询,如下所示:
SELECT customer_id, SUM(amount)
FROM table GROUP BY customer_id
但是我需要能够找到例如某个客户的总金额达到$ 100的日期。
任何帮助是极大的赞赏。 谢谢!
杰西
我相信您正在寻找“运行总额”计算的版本。
看看这篇文章calculate-a-running-total 。 那里有许多有用的链接。
本文还有很多您可以重用的代码: http : //www.sqlteam.com/article/calculating-running-totals 。
像有条款
SELECT customer_id,SUM(amount)作为汇总,来自表GROUP BY customer_id的Total> 100
我不确定MySQL是否支持子查询,因此请一salt而就:
SELECT customer_id
, MIN(created_at) AS FirstDate
FROM ( SELECT customer_id
, created_at
, ( SELECT SUM(amount)
FROM [Table] t
WHERE t.CustomerID = [Table].CustomerID
AND t.created_at <= [Table].created_at
) AS RunTot
FROM [Table]
) x
WHERE x.RunTot >= 100
GROUP BY customer_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.