1

我想得到下表的岛屿:

Group    MemberNo
A           100
A           101
A           200
A           201
A           202
A           203
X           100
X           101
A           204
X           301
X           302
A           500
A           600

我想使用 SQL(岛屿)得到这个结果:

Group  FromMemberNo      ToMemberNo
A             100             101
A             200             204
X             100             101
X             301             302
A             500             500
A             600             600

我已经看到了很多代码/论坛,但没有使用 SQLite,因为 SQLite 没有 CTE。

100-101 是连续的,因此它将被组合为一个。

有谁知道如何在 SQLite 中做到这一点?

4

1 回答 1

1

最快的方法是循环遍历该表的有序记录并手动收集岛屿。

在纯 SQL(作为面向集合的语言)中,这并不容易。

首先,我们找出哪些记录是岛屿中的第一个。第一条记录没有先前的记录,即具有相同组但具有较小组的记录MemberNo

SELECT "Group",
       MemberNo AS FromMemberNo
FROM ThisTable AS t1
WHERE NOT EXISTS (SELECT 1
                  FROM ThisTable AS t2
                  WHERE t2."Group" = t1."Group"
                    AND t2.MemberNo = t1.MemberNo - 1)

要找到一个岛的最后一条记录,我们必须找到最大的记录,MemberNo它仍然属于同一个岛,即具有相同的组,并且MemberNo岛上的所有s都是连续的。MemberNo我们通过计算它们在第一个和最后一个记录中的值之间的差异来检测连续的 s。带有 group和 firstMemberNo的岛的最后一个可以这样计算:GMemberNo M

SELECT MAX(MemberNo) AS LastMemberNo
FROM ThisTable AS t3
WHERE t3."Group" = G
  AND t3.MemberNo - M + 1 = (SELECT COUNT(*)
                             FROM ThisTable AS t4
                             WHERE t4."Group" = G
                               AND t4.MemberNo BETWEEN M AND t3.MemberNo)

最后,将其插入第一个查询:

SELECT "Group",
       MemberNo AS FromMemberNo,
       (SELECT MAX(MemberNo)
        FROM ThisTable AS t3
        WHERE t3."Group" = t1."Group"
          AND t3.MemberNo - t1.MemberNo + 1 = (SELECT COUNT(*)
                                               FROM ThisTable AS t4
                                               WHERE t4."Group" = t1."Group"
                                                 AND t4.MemberNo BETWEEN t1.MemberNo AND t3.MemberNo)
       ) AS LastMemberNo
FROM ThisTable AS t1
WHERE NOT EXISTS (SELECT 1
                  FROM ThisTable AS t2
                  WHERE t2."Group" = t1."Group"
                    AND t2.MemberNo = t1.MemberNo - 1)
于 2013-03-27T08:22:00.090 回答