如何对重复记录进行分组?
我有一列表示记录是开始、结束还是详细记录。详细记录是在开始记录之后和结束记录之前存在的记录。
我想将这些记录与唯一标识符组合在一起,以便每次有结束记录时,下一系列记录都会获得一个新的组 ID。
我已经尝试了一系列自连接、子查询和 cte,但没有构建自定义函数、视图或 CTE,我希望在单个选择查询中构建它。
非常感谢任何建议或指示。
解决方案前的示例:
--------------------------------------------------
| ID | RecordType | SomeValue
--------------------------------------------------
|001 | Start record | some header info
|002 | Detail Record | value
|003 | Detail Record | value
|004 | Detail Record | value
|005 | End Record | some other header info
|006 | Start Record | some header info
|007 | Detail Record | Value
|008 | End Record | some other header info
我试图实现的目标:
------------------------------------------------------------------
| ID | RecordType | SomeValue | RecordGroup
------------------------------------------------------------------
|001 | Start record | some header info | 001
|002 | Detail Record | value | 001
|003 | Detail Record | value | 001
|004 | Detail Record | value | 001
|005 | End Record | some other header info| 001
|006 | Start Record | some header info | 002
|007 | Detail Record | Value | 002
|008 | End Record | some other header info| 002
您可以使用该LAG
功能并运行SUM
. 以下假设没有分区并且行按 ID 排序:
SELECT ID, RecordType, SomeValue,
SUM(chg) OVER (ORDER BY ID) AS grp
FROM (
SELECT ID, RecordType, SomeValue,
CASE WHEN LAG(RecordType) OVER (ORDER BY ID) IN ('Start record', 'Detail Record') THEN 0 ELSE 1 END AS chg
FROM t
) cte1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句