日期:2014-05-17 浏览次数:20535 次
--> 测试数据:[tb]
IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]
GO
CREATE TABLE [tb]([ID] INT,[CPBH] INT,[XH] VARCHAR(3))
INSERT [tb]
SELECT 1,231120,'A-1' UNION ALL
SELECT 2,231124,'A-2' UNION ALL
SELECT 3,261534,'A-3' UNION ALL
SELECT 4,271280,'B-1' UNION ALL
SELECT 5,271284,'B-2'
--------------开始查询--------------------------
SELECT * FROM [tb] AS t WHERE NOT EXISTS (SELECT 1 FROM [tb] WHERE LEFT([CPBH],5)=LEFT(t.[CPBH],5) AND [ID]<>t.[ID] AND RIGHT(t.[CPBH],1)<>0 )
----------------结果----------------------------
/*
ID CPBH XH
1 231120 A-1
3 261534 A-3
4 271280 B-1
*/
CREATE TABLE #MM (
ID INT IDENTITY(1,1),
CPBH INT ,
XH CHAR(5)
)
INSERT #MM
SELECT 231120 ,'A-1'
UNION ALL
SELECT 231124, 'A-2'
UNION ALL
SELECT 261534, 'A-3'
UNION ALL
SELECT 271280, 'B-1'
UNION ALL
SELECT 271284,'B-2'
SELECT * FROM #MM WHERE ID IN(
SELECT MIN(ID) FROM #MM GROUP BY LEFT(CPBH,5)
)