MySQl查询选择计数,直到达到特定值

时间:2014-09-08 09:53:55

标签: mysql

我有这张表,例如:

Id   StatusDate   Status
1    20-08-2014    
1    15-08-2014
1    09-08-2014     P
2    17-08-2014
1    10-08-2014
2    12-08-2014
2    06-07-2014     P
1    30-07-2014     
2    02-07-2014   
2    01-07-2014     P

......等等

我想在状态为空的情况下选择ID,直到我点击第一个' P'按ID按日期组的升序排列。所以我的结果将是这样的。

ID    Count
1     3
2     2

3 个答案:

答案 0 :(得分:1)

试一试。未经测试

SELECT t1.ID, count(*) FROM table t1 
WHERE t1.StatusDate >= (SELECT MAX(t2.StatusDate) FROM table t2 
                     WHERE t1.ID = t2.ID AND t2.Status = 'P') 
GROUP BY t1.ID

答案 1 :(得分:0)

一个选项是使用statusDate值较低的JOIN和COUNT行,如下所示:

SELECT t1.id, SUM(CASE WHEN t1.statusdate > t2.statusdate THEN 1 ELSE 0 END) AS mycount
FROM t t1 JOIN (
  SELECT id, MIN(statusdate) statusdate
  FROM t
  WHERE status = 'P'
  GROUP BY id
  ) t2
ON t1.id = t2.id 
GROUP BY t1.id

工作演示:http://sqlfiddle.com/#!2/d9d91/2

答案 2 :(得分:0)

假设您的表名为StatusTable这将起作用:

SELECT 
    ID, 
    COUNT(*) AS `Count` 
FROM StatusTable AS st 
WHERE 
    st.Status = ''
    AND st.StatusDate > (
        SELECT st2.StatusDate 
        FROM `StatusTable` AS st2 
        WHERE st.ID = st2.ID 
            AND st2.Status = 'P' 
        ORDER BY st2.StatusDate DESC 
        LIMIT 1
    ) 
GROUP BY st.ID
ORDER BY st.ID