要加字段id
程序代码:
DECLARE @t TABLE( id INT, name VARCHAR(10))
INSERT @t
VALUES
( 1, '王五' ),
( 2, '王五' ),
( 3, '王五' ),
( 4, '李三' ),
( 5, '王五' ),
( 6, '赵四' ),
( 10, '田强' ),
( 15, '田强' ),
( 18, '李三' )
SELECT * FROM @t AS T
--第一种
DECLARE @th TABLE( rank1 INT, id INT, name VARCHAR(10))
INSERT @th SELECT ROW_NUMBER() OVER ( ORDER BY T.id ), T.id, T.name FROM @t AS T
SELECT A.id, A.name
FROM @th A
LEFT JOIN @th B ON B.rank1 - 1 = A.rank1
WHERE A.name <> B.name
OR B.name IS NULL
--第二种
DECLARE @th2 TABLE( id INT, name VARCHAR(10), GroupKey VARCHAR(20))
INSERT @th2
SELECT *,
CONCAT(
ROW_NUMBER() OVER ( ORDER BY T.id ) - ROW_NUMBER() OVER ( PARTITION BY T.name ORDER BY T.id ),
'|',
T.name) groupkey
FROM @t AS T
--SELECT * FROM @th2 AS T
SELECT MAX(T.id) id, MAX(T.name) name FROM @th2 AS T GROUP BY GroupKey ORDER BY id
[此贴子已经被作者于2021-4-25 13:52编辑过]