MYSQL选择不超过必要的行

时间:2018-02-26 13:43:25

标签: mysql select

表:

ID | DATETIME (YmdHis) | MONEY | USERID
========================================
1  | 20180219120011    | 200   | 1
2  | 20180220041910    | 20    | 2
3  | 20180221185913    | 53    | 1
4  | 20180222165934    | 220   | 2
5  | 20180222015925    | 10    | 1
6  | 20180223021205    | 30    | 1
7  | 20180224034909    | 20    | 2
8  | 20180224034909    | 35    | 2
9  | 20180226021205    | 55    | 1
10 | 20180226021205    | 115   | 2

当特定用户的MONEY SUM达到特定数量而不是更多时,我需要选择仅行。并按DATETIME ASC排序这些行。
USERID和SUM是输入数据 例如,
1)对于SUM = 250和USERID = 1,我需要得到那些行ID:1和3(SUM = 253)。
2)对于SUM = 250和USERID = 2,我需要得到那些行ID:2,4和7(SUM = 260)。

2 个答案:

答案 0 :(得分:1)

在此解决方案中,最里面的查询按id顺序计算用户ID的累计金额总额,下一个最里面的查询(s1)计算出最早的id,其中累积和> = 250且最外面的查询加入所有ids< =由s1找到的迷你。

select t.*
from t
join
(
select userid,min(id) minid
from
(
select id,money,userid,
         (select sum(t1.money) from t t1 where t1.USERID = t.userid and t1.id <= t.id) cumsum
from t 
order by userid ,id
) s 
where cumsum >= 250
group by userid
) s1 on s1.userid = t.userid and t.id <= s1.minid
order by t.userid, t.id

结果

+------+-------+--------+
| ID   | MONEY | USERID |
+------+-------+--------+
|    1 |   200 |      1 |
|    3 |    53 |      1 |
|    2 |    20 |      2 |
|    4 |   220 |      2 |
|    7 |    20 |      2 |
+------+-------+--------+
5 rows in set (0.00 sec)

答案 1 :(得分:-1)

SELECT table_name.* 
FROM table_name INNER JOIN 
     (SELECT USERID, SUM(MONEY) 
      FROM table_name 
      GROUP BY USERID 
      HAVING SUM(MONEY) >= 250) AS helper 
ON table_name.USERID = helper.USERID 
ORDER BY DATETIME;