在特定条件匹配后分组

时间:2016-01-25 11:35:09

标签: mysql sql

考虑下面的transactions表格

+----+---------+-------+--------+
| id | user_id | value | tag    |
+----+---------+-------+--------+
|  1 |       1 |    30 | ''     |
|  2 |       1 |    20 | 'foo'  |
|  3 |       1 |   -10 | ''     |
|  4 |       2 |    60 | ''     |
|  5 |       2 |    30 | 'foo'  |
|  6 |       2 |   -25 | ''     |
+----+---------+-------+--------+

我希望按user_id分组,获取sum(value),以便在匹配代码后获取行" foo " (其id的行大于匹配的行)

例如,上表,我想得到以下内容

+---------+-------+
| user_id | value |
+---------+-------+
|       1 |    10 |
|       2 |     5 |
+---------+-------+

2 个答案:

答案 0 :(得分:3)

您可以使用自我加入:

SELECT t1.user_id, SUM(t2.`value`) AS `value`
FROM transactions t1
JOIN transactions t2
  ON t1.user_id = t2.user_id
 AND t1.id <= t2.id
WHERE t1.tag = 'foo'
GROUP BY t1.user_id;

LiveDemo

输出:

╔═════════╦═══════╗
║ user_id ║ value ║
╠═════════╬═══════╣
║       1 ║    10 ║
║       2 ║     5 ║
╚═════════╩═══════╝

答案 1 :(得分:0)

select user_id, sum(value)
from transactions as t1
where id >=
   ( select min(id)  -- find the 1st 'foo' id for each user
     from transactions as t2
     where tag = 'foo'
       and t1.user_id = t2.user_id
   )
group by user_id