日期:2014-05-17 浏览次数:20430 次
--> 测试数据:[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([id] INT,[name] VARCHAR(7)) INSERT [tb] SELECT 1,'AA333AB' UNION ALL SELECT 2,'AA555AB' UNION ALL SELECT 3,'BB666AC' UNION ALL SELECT 4,'BB555AC' UNION ALL SELECT 5,'CC777' --------------开始查询-------------------------- SELECT * FROM [tb] AS t WHERE NOT EXISTS (SELECT 1 FROM tb WHERE SUBSTRING([name],3,3)=SUBSTRING(t.[name],3,3) AND id<t.id ) ----------------结果---------------------------- /* id name ----------- ------- 1 AA333AB 2 AA555AB 3 BB666AC 5 CC777 (4 行受影响) */
------解决方案--------------------
select * from tb t where id=(select min(id) from tb where substring(name,3,3)=substring(t.name,3,3))
------解决方案--------------------
DECLARE @TABLE1 TABLE([ID] INT,[NAME] VARCHAR(7)) INSERT @TABLE1 SELECT 1,'AA333AB' UNION ALL SELECT 2,'AA555AB' UNION ALL SELECT 3,'BB666AC' UNION ALL SELECT 4,'BB555AC' UNION ALL SELECT 5,'CC777' SELECT * FROM @TABLE1 T WHERE ID=(SELECT MIN(ID) FROM @TABLE1 WHERE SUBSTRING(NAME,3,3)=SUBSTRING(T.NAME,3,3)) /* ID NAME ----------- ------- 1 AA333AB 2 AA555AB 3 BB666AC 5 CC777 */