我正在尝试使用以下查询确定哪一列与前一行不同。我想知道是否有更好的,即更有效的方式?我认为这是一个非常通用的问题,但我意识到我有一种与前一行比较的特殊方法,因为我不考虑第二行中的空值来添加与前一行相比的任何内容。我想这些规则可以调整,但有一般方法。
SELECT pc,
id1,
id2,
id3,
id4,
CASE
WHEN pcp is null or pc!=pcp
THEN 0
WHEN id1 IS NOT NULL
AND (id1p IS NULL
OR id1! =id1p)
THEN 1
WHEN id2 IS NOT NULL
AND (id2p IS NULL
OR id2! =id2p)
THEN 2
WHEN id3 IS NOT NULL
AND (id3p IS NULL
OR id3! =id3p)
THEN 3
WHEN id4 IS NOT NULL
AND (id4p IS NULL
OR id4! =id4p)
THEN 4
ELSE -1
END first_diff_col,endpos
FROM
(SELECT pc,
id1,
id2,
id3,
id4,
lag(pc,1) over (order by pc,id1,id2,id3,id4) pcp,
lag(id1,1) over (order by pc,id1,id2,id3,id4) id1p,
lag(id2,1) over (order by pc,id1,id2,id3,id4) id2p,
lag(id3,1) over (order by pc,id1,id2,id3,id4) id3p,
lag(id4,1) over (order by pc,id1,id2,id3,id4) id4p,
CASE WHEN id1 is null THEN 0
WHEN id2 is null THEN 1
WHEN id3 is null THEN 2
WHEN id4 is null THEN 3
ELSE 4
END endpos
FROM test_table
ORDER BY pc,
id1,
id2,
id3,
id4
);