SQL-SQLite计数连续数
我有一个包含以下数据的表格:SQL-SQLite计数连续数,sql,sqlite,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 |
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
. . ....... . ...................
在这个示例表中,我使用类似的查询来计算数字,例如:
select count(*) from table where numbers like '%-4-%'
Result: 5
现在,我如何计算(使用like)一个数字连续出现多少次(在本例中是数字4)?
我的意思是:数字4连续出现在id 1,2,3和5,6上,所以我想得到一个结果为: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
[[编辑:添加测试数据并更正引用]]
[[编辑:将查询更改为仅在有至少两个成员的行组的情况下计数]并且您还希望在数字为1的情况下点击id=1,2,5,6?它必须返回1,2作为单独的“命中”还是1,2,5,6就足够了?谢谢你的回答Lance:)你的解决方案很好,但是如果我在数字5上执行你的查询(例如),它会给我结果1而不是0。我的意思是我只想数一数连续的数字,不包括单个数字。另一个示例:-1-3-5-|-2-4-6-|-1-3-7-|-1-4-6-数字1的结果查询应该是1而不是2。如何修改您的查询以执行此操作?再次感谢:)