我有以下 示例数据
ID Category Status Seq Start DT End DT
1 CAT 1 U 1 17-Feb-11 17-Feb-11
1 CAT 1 I 2 17-Feb-11 17-Feb-11
1 CAT 1 X 0 17-Feb-11 3-Mar-11
1 CAT 1 X 0 3-Mar-11 4-Mar-11
1 CAT 1 X 0 4-Mar-11 28-Jun-11
1 CAT 1 I 6 28-Jun-11 29-Jun-11
1 CAT 1 X 0 29-Jun-11 15-Jul-11
1 CAT 1 X 0 15-Jul-11 28-Jul-11
1 CAT 1 X 0 28-Jul-11 28-Jul-11
1 CAT 1 I 10 28-Jul-11 1-Aug-11
1 CAT 1 D 11 1-Aug-11 8-Aug-11
1 CAT 1 E 0 8-Aug-11 9-Aug-11
1 CAT 1 E 0 9-Aug-11 1-Sep-11
1 CAT 1 E 0 1-Sep-11 13-Sep-11
预期输出: -
ID Category Status Seq Start DT End DT
1 CAT 1 U 1 17-Feb-11 17-Feb-11
1 CAT 1 I 2 17-Feb-11 17-Feb-11
1 CAT 1 X 0 17-Feb-11 3-Mar-11
1 CAT 1 X 0 3-Mar-11 4-Mar-11
1 CAT 1 X 0 4-Mar-11 28-Jun-11
1 CAT 1 I 6 28-Jun-11 29-Jun-11
1 CAT 1 X ***0A*** 29-Jun-11 15-Jul-11
1 CAT 1 X ***0A*** 15-Jul-11 28-Jul-11
1 CAT 1 X ***0A*** 28-Jul-11 28-Jul-11
1 CAT 1 I 10 28-Jul-11 1-Aug-11
1 CAT 1 D 11 1-Aug-11 8-Aug-11
1 CAT 1 E 0 8-Aug-11 9-Aug-11
1 CAT 1 E 0 9-Aug-11 1-Sep-11
1 CAT 1 E 0 1-Sep-11 13-Sep-11
" seq"列是sql生成的列,基本上是rownum。对于状态列中的同一组值," seq"值应该保持相同,例如在这种情况下为0。但对于下一组相同的状态值," seq"值应该是与前一个不同的值,例如0A。对于所有其他情况,seq值将只是rownum。 感谢
答案 0 :(得分:2)
如果仅为所有组获取单独的值,则可以使用SUM() OVER()
子句生成组名。在这里,我假设ORDER BY "Start DT", "End DT", "Seq"
足以获得行的正确排序,因此如果不正确,您可能需要调整它。
WITH cte AS (
SELECT "ID", "Category", "Status", "Seq", "Start DT", "End DT",
SUM("Seq") OVER (ORDER BY "Start DT", "End DT", "Seq") "Seq2"
FROM mytable
)
SELECT "ID", "Category", "Status",
CASE WHEN "Seq"=0
THEN 'A' || CAST("Seq2" AS VARCHAR(32))
ELSE CAST("Seq" AS VARCHAR(32))
END "Seq",
"Start DT", "End DT"
FROM cte
由于我们要分组的值的值为0,因此SUM将为每一行生成相同的值(因为当我们添加0时总和不会改变),因此我们可以使用该总和生成组名。