如何在mysql查询中应用计数条件

时间:2014-11-13 07:04:03

标签: mysql

2,0 - 开放,2,1 - 待定,2,2 - 关闭

需要建议查看所有在关闭后再次打开的门票(2,2)

id   c_id  type   value  created_at

1    201    2       0     
2    201    2       1
3    201    2       2
4    201    2       0
5    201    2       2
6    201    2       0
7    201    2       1
8    201    2       2

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT *
FROM mytable
WHERE id IN(
    SELECT id
    FROM mytable
    WHERE type = 2
    AND value = 2
    )
AND type != 2
AND value != 2

答案 1 :(得分:0)

假设c_id是故障单的标识符,并假设id列用于确定一个事件是在“另一个事件之后”......

SELECT o.c_id
  FROM mytable o        -- open events
  JOIN mytable c        -- close events
    ON c.c_id = o.c_id  -- match same ticket
   AND c.type = 2 
   AND c.value = 2      -- close event
   AND c.id < o.id      -- close event is before open
 WHERE o.type = 2 
   AND o.value = 0      -- open event
 GROUP BY o.c_id        -- distinct list of ticket