SQL - SQLite计算连续数字

时间:2009-10-30 04:48:26

标签: 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。

1 个答案:

答案 0 :(得分: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个成员的行组时才计算]]