问题
Consider the scheme below
id user tag created
1 foo tag1 2018-09-01
2 foo tag2 2018-09-01
3 bar tag1 2018-09-02
4 bar tag2 2018-09-03
5 kkk tag2 2018-09-05
6 qqq tag1 2018-09-12
How to find the number of unique user, which after the row 'tag1' there is a 'tag2' followed in future row of that user?
The answer is 2
(foo,bar), based on the above query
回答1:
You can use aggregation to get the list of users:
select user
from t
group by user
having min(case when tag = 'tag1' then created end) < max(case when tag = 'tag2' then created end);
To get the number of such users, use a subquery:
select count(*)
from (select user
from t
group by user
having min(case when tag = 'tag1' then created end) < max(case when tag = 'tag2' then created end)
) u;
回答2:
You can use a sub query to find such rows:
SELECT *
FROM yourdata AS t
WHERE tag = 'tag1'
AND EXISTS (
SELECT 1
FROM yourdata AS x
WHERE x.user = t.user
AND x.tag = 'tag2'
AND (x.created > t.created OR x.id > t.id)
)
来源:https://stackoverflow.com/questions/52366225/mysql-count-on-precondition