0

我想用序号装饰表中每个重复组的每个成员。因此对于:

id    fk    scheme    code
1     23    2         1234
2     23    2         6666
3     23    2         9876
4     24    2         3421
5     24    5         erty
6     24    7         wert
7     25    2         3490
8     25    2         2389
9     25    5         erfg

我会在我的结果中看到

23|2|1  1234
23|2|2  6666
23|2|3  9876
24|2|1  3421
24|5|1  erty
24|7|1  wert
25|2|1  3490
25|2|2  2389
25|5|1  erfg

因此 fk 与 scheme 结合构成​​一个重复组。我知道我在重复组中最多只有 5 个,但我的测试查询只允许 3 个。连续的行号不能作为装饰,它必须是 1 或 2 或 3,因为它们用于缓存查找。

这是我使用 H2 Db SQL 语法提出的 SQL:

SELECT "identifier", "code" FROM (
SELECT CASE WHEN s1."code" IS NOT NULL AND s2."code" IS NULL AND s3."code" IS NULL 
THEN s1."ident"||'|1' 
WHEN s1."code" IS NOT NULL AND s2."code" IS NOT NULL AND s3."code" IS NULL
THEN s2."ident"||'|2' 
WHEN  s1."code" IS NOT NULL AND s2."code" IS NOT NULL AND s3."code" IS NOT NULL
THEN s3."ident"||'|3' END AS "identifier", s1."code"
FROM (select "ii"."fk", "ii"."scheme", "ii"."fk"||'|'||"ii"."scheme" AS "ident", "code"
from "inidentifier" "ii" group by "fk", "scheme", "code") s1 
LEFT OUTER JOIN
(select "ii"."fk", "ii"."scheme", "ii"."fk"||'|'||"ii"."scheme" AS "ident", "code" 
from "inidentifier" "ii" group by "fk", "scheme", "code") s2 ON s1."ident" = s2."ident"
AND s1."code" < s2."code"
LEFT OUTER JOIN
(select "ii"."fk", "ii"."scheme", "ii"."fk"||'|'||"ii"."scheme" AS "ident", "code"
from "inidentifier" "ii" group by "fk", "scheme", "code") s3 ON  s1."ident" = s2."ident"
AND s2."ident" = s3."ident" AND s1."code" < s2."code" AND s2."code" < s3."code"
ORDER BY "identifier", s1."code") "cache"
WHERE "cache"."identifier" IS NOT NULL

我遇到的问题是它不会产生任何最后带有 |3 的结果,在上面的示例数据中应该有 1。它以 23|2|2 9876 和 23|2|2 6666 结束。也许不同的方法?

先感谢您

大卫

4

1 回答 1

0

如果任何 DBMS 都可以,那么自然的方法是row_number()

select  *
,       row_number() over (partition by fk, scheme order by id) as rn
from    YourTable

这将为组中的每一行返回一个序号(fk, scheme)

于 2012-06-13T07:43:30.867 回答