I have a table with the following data:
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
. . ....... . ...................
In this example table I use a like
query to count numbers, example:
select count(*) from table where numbers like '%-4-%'
Result: 5
Now, how can I count (using like) how many times a number appears consecutively (in this case the number 4)? I mean: the number 4 appears consecutively on id 1,2,3 and 5,6 so I want to get a query with result: 2.
This should do it.
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
[[Edit: Added test data and corrected quoting]]
[[Edit: Changed query to only count only where there are row groups with at least 2 members]]
精彩评论