基于值计算天数序列的SQL查询

时间:2013-03-26 09:58:38

标签: sql sql-server

我的表格包含idtimestamp和控制值。

我需要查询具有控制值0的ID,连续4天或更长时间

TimeS   ID  Kontrol
2012-06-18  5457554F-E9A5-4312-8BA3-424B2333D0B7    1
2012-06-14  3FC4AC80-7D94-496A-92D0-22350CA3CEA9    1
2012-06-14  FE3C1872-0F13-48CC-A6C9-BBE0EAB07B9D    0
2012-06-13  FE3C1872-0F13-48CC-A6C9-BBE0EAB07B9D    0
2012-06-12  FE3C1872-0F13-48CC-A6C9-BBE0EAB07B9D    0
2012-06-11  FE3C1872-0F13-48CC-A6C9-BBE0EAB07B9D    0

例如,它应该返回FE3C1872-0F13-48CC-A6C9-BBE0EAB07B9

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT t1.id
  FROM tableName t1
 WHERE t1.kontrol = 0
   AND EXISTS (SELECT 1
                 FROM tableName t2
                WHERE t2.id = t1.id
                  AND t2.kontrol = 0
                  AND t2.timeS = t1.timeS + 1
                  AND EXISTS (SELECT 1
                                 FROM tableName t3
                                WHERE t3.id = t2.id
                                  AND t3.kontrol = 0
                                  AND t3.timeS = t2.timeS + 1
                                  AND EXISTS (SELECT 1
                                                FROM tableName t4
                                               WHERE t4.id = t3.id
                                                 AND t4.kontrol = 0
                                                 AND t4.timeS = t3.timeS + 1)))

答案 1 :(得分:0)

SELECT DISTINCT t1.id
FROM table t1
     INNER JOIN 
     table t2 ON t2.TimeS+1 days=t1.TimeS
     INNER JOIN 
     table t3 ON t3.TimeS+2 days=t1.TimeS
     INNER JOIN 
     table t4 ON t4.TimeS+3 days=t1.TimeS
WHERE t1.Control = 0 AND
      t2.Control = 0 AND
      t3.Control = 0 AND
      t4.Control = 0

答案 2 :(得分:0)

尝试此查询

select 
  id, 
  count(distinct TimeS) 
from 
  table1
where 
  kontrol=0
group by 
  id 
having 
  count(distinct TimeS) >= 4;

<强> FIDDLE