tags:

views:

154

answers:

1

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.

+2  A: 

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]]

Lance Rushing
Thanks for your reply Lance :)Your solution is good, but if I execute your query on number 5 (for example) it give me result 1 and not 0.I mean that I wanna count only consecutive numbers excluding single number. Another example: -1-3-5- |-2-4-6- |-1-3-7- |-1-4-6- the result query for number 1 should be 1 and not 2. How can I modify your query for do it? Thanks again :)
Maiori
ah.. ok exclude single numbers... working on it,
Lance Rushing
ok, thanks you so much :)
Maiori