2013-03-26 107 views
0

我有表id,timestamp和控制值。SQL查詢計算基於某個值的天數

我需要ID查詢其在序列

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 

具有控制值0 4天或更應該例如返回FE3C1872-0F13-48CC-A6C9-BBE0EAB07B9

+0

。 Okey我會發布一些數據 – 2013-03-26 10:02:53

+0

你認爲這是很好的樣本數據嗎?根據你的定義沒有記錄顯示。 – 2013-03-26 10:25:15

+0

Okey編輯 – 2013-03-26 10:27:42

回答

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))) 
+0

不限於連續的日子 – 2013-03-26 10:23:51

+0

它不確保日期 – 2013-03-26 10:24:36

+0

@efe demir:編輯。請嘗試這個新的解決方案。 – Rachcha 2013-03-26 10:33:20

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 
+0

您可以再次檢查問題請 – 2013-03-26 10:31:47

+0

查詢看起來不錯,對於您的RDMS,您可能需要調整添加天 – 2013-03-26 10:34:35

+0

您忘記加入ID ,但這樣的事情應該工作 – 2013-03-26 10:40:18

0

嘗試此查詢

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

FIDDLE

使用MSSQL林
+0

_「其具有控制值0 ** 4天或更長時間** 「_所以,即使你會採取行動日期考慮在內,這些時間範圍內的其他控制值不應該中斷。 – 2013-03-26 10:55:44

+0

此查詢中TimeS不連續 – 2013-03-26 11:27:47