选择在该期间首次付款期间的付款总额

时间:2014-03-31 11:34:58

标签: mysql select

我有付款表' user_id - 已创建 - 价格'。 我需要计算3月14日至16日期间所有付款的总和,其中第一笔付款是在同一时期内支付的

我遇到的最佳解决方案是

 SELECT user_id, SUM(price/100) FROM payment WHERE
 (DATE(created) BETWEEN '2014-03-14' AND '2014-03-16')
 AND (MIN(created) BETWEEN '2014-03-14 00:00:01' AND '2014-03-16 23:59:59')
 GROUP BY user_id

但我得到了#34;无效使用群组功能"

更新: 这个请求解决了我的问题

SELECT p.user_id, SUM(p.price/100) FROM payment p WHERE
(DATE(created) BETWEEN '2014-03-14' AND '2014-03-16')
AND (SELECT MIN(DATE(created)) FROM payment WHERE user_id = p.user_id) BETWEEN '2014-03-14' AND '2014-03-16'
GROUP BY p.user_id

1 个答案:

答案 0 :(得分:0)

您不能在where子句中使用MIN()函数,您需要使用HAVING来过滤您可以重写查询的聚合函数,如下所示

 SELECT user_id, SUM(price/100) 
 FROM payment 
 WHERE
 created BETWEEN '2014-03-14 00:00:00' AND '2014-03-16 23:59:59'
 GROUP BY user_id
 HAVING MIN(created) BETWEEN '2014-03-14 00:00:00' AND '2014-03-16 23:59:59'