当产生新数据,向另一表填入数据
TAB1
ID CPBH XH
1 231120 A-1
2 231124 A-2
3 261534 A-3
4 271280 B-1
5 271284 B-2
...
说明:TAB1有目前9000多条数据,而且每天都有新数据增加,现在用户要求:
如果CPBH 的前5位数据一样,则取第6位后缀为 0 的数据,生成新表
TAB2
ID CPBH XH
1 231120 A-1
3 261534 A-3
4 271280 B-1
...
如何处理,请高手指点,谢谢
[最优解释]
--> 测试数据:[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 )
----------------结果----------------------------
/*
IDCPBHXH
1231120A-1
3261534A-3
4271280B-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)
)
select a.* from #mm a
join (
select MIN(cpbh) as cpbh from #MM
group by LEFT(cpbh,5)) as b on a.cpbh=b.cpbh