请教一个问题,如此数据冗余如何删除
数据表:
CREATE TABLE tb_Table
(
ID int IDENTITY(1,1) NOT NULL,
GeoNO varchar(50) NOT NULL,
Title varchar(100) NULL,
ConID varchar(50) NULL
)
Insert into tb_Table (GeoNo,Title,ConID) values ('01','北京','1000')
Insert into tb_Table (GeoNo,Title,ConID) values ('0101','海淀区','1000')
Insert into tb_Table (GeoNo,Title,ConID) values ('010101','上地','1000')
Insert into tb_Table (GeoNo,Title,ConID) values ('01','北京','1001')
Insert into tb_Table (GeoNo,Title,ConID) values ('0102','朝阳区','1001')
Insert into tb_Table (GeoNo,Title,ConID) values ('010201','北辰','1001')
Insert into tb_Table (GeoNo,Title,ConID) values ('01','北京','1002')
Insert into tb_Table (GeoNo,Title,ConID) values ('0103','昌平区','1002')
Insert into tb_Table (GeoNo,Title,ConID) values ('010301','回龙观','1002')
我想把上述数据入库后,再从表里删除数据,保留的数据是:
'010101','上地','1000'
'010201','北辰','1001'
'010301','回龙观','1002'
其他的数据则删除,即保证ConID是唯一的,而且GeoNo的值是最大。如何用SQL来实现?
谢谢!
------解决方案--------------------SQL code
DELETE FROM T1
FROM TB_TABLE T1
WHERE EXISTS(
SELECT 1 FROM TB_TABLE T2 WHERE T2.CONID=T1.CONID AND LEN(T2.GEOID)>LEN(T1.GEOID)
)
------解决方案--------------------
SQL code
delete t from tb_Table t
where exists( select 1 from tb_Table where ConID=t.ConID and GeoNo>t.GeoNo)
------解决方案--------------------
SQL code
DELETE FROM TB_TABLE T1
WHERE EXISTS(
SELECT 1 FROM (select max(GEOID) as GEOID,CONID from TB_TABLE group by CONID) T2 WHERE T2.CONID=T1.CONID AND T2.GEOID>T1.GEOID)
------解决方案--------------------
SQL code
--这样似乎更合理点。
delete t from tb_Table t
where exists( select 1 from tb_Table where ConID=t.ConID and len(GeoNo)>len(t.GeoNo))
------解决方案--------------------
SQL code
DELETE FROM T1
FROM TB_TABLE T1
WHERE EXISTS(
SELECT 1 FROM TB_TABLE T2 WHERE T2.CONID=T1.CONID AND LEN(T2.GEOID)>LEN(T1.GEOID)
)