【问题标题】:SQL - SQLite count consecutive numbersSQL - SQLite 计算连续数字
【发布时间】:2009-10-30 04:48:25
【问题描述】:

我有一个包含以下数据的表格:

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

现在,我如何计算(使用like)一个数字连续出现多少次(在本例中为数字4)? 我的意思是:数字 4 在 id 1,2,3 和 5,6 上连续出现,所以我想得到一个结果为 2 的查询。

【问题讨论】:

  • 您还想在数字为 1 的情况下点击 id=1,2,5,6 吗?它必须返回 1,2 作为单独的“命中”还是 1,2,5,6 就足够了?

标签: sql sqlite


【解决方案1】:

应该这样做。

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 个成员的情况下计算]]

【讨论】:

  • 感谢您的回复 Lance :) 您的解决方案很好,但如果我对 5 号(例如)执行您的查询,它会给我结果 1 而不是 0。我的意思是我只想计算连续数字不包括单个数字。另一个例子:-1-3-5- | -2-4-6- | -1-3-7- | -1-4-6- 数字 1 的结果查询应该是 1 而不是 2。我该如何修改您的查询呢?再次感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 2010-12-06
  • 2011-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多