日期:2014-05-17 浏览次数:20367 次
--> 测试数据:[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([id] INT,[name] VARCHAR(4)) INSERT [tb] SELECT 1,'张三' UNION ALL SELECT 2,'张三' UNION ALL SELECT 3,'李四' UNION ALL SELECT 4,'王五' UNION ALL SELECT 5,'张三' UNION ALL SELECT 8,'张三' UNION ALL SELECT 9,'张三' UNION ALL SELECT 11,'张三' UNION ALL SELECT 12,'王五' --------------开始查询-------------------------- --1 ;WITH cte AS ( SELECT *,row_id=ROW_NUMBER() OVER(ORDER BY id) FROM [tb] ) SELECT id=ROW_NUMBER() OVER(ORDER BY id),name FROM cte AS a WHERE NOT EXISTS(SELECT 1 FROM cte WHERE [name]=a.[name] AND [row_id]=a.[row_id]-1 ) --2 SELECT id=ROW_NUMBER() OVER(ORDER BY id),name FROM [tb] AS a WHERE NOT EXISTS(SELECT 1 FROM [tb] WHERE [name]=a.[name] AND [id]=a.[id]-1 )
------解决方案--------------------
DENSE_RANK ( ) OVER ( [ <partition_by_clause> ] < order_by_clause > )