2009-10-30 78 views
1

我有下列數據的表:SQL - SQLite的計數連續編號

id | numbers | date 
---------------------------------- 
1 | -1-4-6- | 2009-10-26 15:30:20 
2 | -1-4-7- | 2009-10-26 16:45:10 
3 | -4-5-8- | 2009-10-27 11:21:34 
4 | -2-6-7- | 2009-10-27 13:12:56 
5 | -1-3-4- | 2009-10-28 14:22:14 
6 | -1-2-4- | 2009-10-29 20:28:16 
. . ....... . ................... 

在這個例子表我用一個like查詢統計的數字,例如:

select count(*) from table where numbers like '%-4-%' 
Result: 5 

現在,如何我可以計算(使用像)一個數字連續出現多少次(在這種情況下是數字4)? 我的意思是:4號連續出現在ID 1,2,3和5,6,所以我想有結果的查詢:2

+0

你對於編號爲1的情況,還希望命中id = 1,2,5,6?它是否必須作爲單獨的「命中」返回1,2或者1,2,5,6是否足夠? – jcollum 2009-10-30 04:52:21

回答

2

這應該這樣做。

create table "table" (id int, numbers text); 
insert into "table" values (1, '-1-4-6-'); 
insert into "table" values (2, '-1-4-7-'); 
insert into "table" values (3, '-4-5-8-'); 
insert into "table" values (4, '-2-6-7-'); 
insert into "table" values (5, '-1-3-4-'); 
insert into "table" values (6, '-1-2-4-'); 

SELECT count(*) 
FROM (
    SELECT "table".*, temp1.id, temp2.id 
    FROM "table" 
    INNER JOIN "table" temp1 
     ON "table".id = temp1.id+1 
    LEFT JOIN (
     SELECT id FROM "table" WHERE numbers LIKE '%-4-%' 
    ) temp2 ON temp1.id+1 = temp2.id+2 

    WHERE "table".numbers LIKE '%-4-%' 
     AND "temp1".numbers LIKE '%-4-%' 
     AND temp2.id IS NULL 
) consecutive_groups_gt_1 

[編輯:添加測試數據和糾正報價]

[編輯:更改的查詢只只能算哪裏有行組至少有2名成員]

+0

感謝您的回覆蘭斯:) 你的解決方案是好的,但如果我執行的5號(例如)查詢它給我造成1和不爲0 我的意思是我想只計數連續的數字不包括單數。另一個例子: -1-3-5- | -2-4-6- | -1-3-7- | -1-4-6- 爲1號的查詢結果應該是1,而不是2.如何修改您的查詢做呢?再次感謝:) – Maiori 2009-10-30 14:49:43

+0

啊..好吧排除單數...它的工作, – 2009-10-30 16:46:35

+0

好的,謝謝你這麼多:) – Maiori 2009-10-30 18:42:04