MySQL count on precondition?

六眼飞鱼酱① 提交于 2019-12-11 17:02:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!