易截截图软件、单文件、免安装、纯绿色、仅160KB

SQL 删除重复数据,只保留1条

if not object_id('Tempdb..#T') is null
    drop table #T
Go
Create table #T([ID] int,[Name] nvarchar(1),[Memo] nvarchar(2))
Insert #T
select 1,N'A',N'A1' union all
select 2,N'A',N'A2' union all
select 3,N'A',N'A3' union all
select 4,N'B',N'B1' union all
select 5,N'B',N'B2'
Go
--I、Name相同ID最小的记录(推荐用1,2,3),保留最小一条
方法1:
delete a from #T a where  exists(select 1 from #T where Name=a.Name and ID<a.ID)
方法2:
delete a  from #T a left join (select min(ID)ID,Name from #T group by Name) b on a.Name=b.Name and a.ID=b.ID where b.Id is null
方法3:
delete a from #T a where ID not in (select min(ID) from #T where Name=a.Name)
方法4(注:ID为唯一时可用):
delete a from #T a where ID not in(select min(ID)from #T group by Name)
方法5:
delete a from #T a where (select count(1) from #T where Name=a.Name and ID<a.ID)>0
方法6:
delete a from #T a where ID<>(select top 1 ID from #T where Name=a.name order by ID)
方法7:
delete a from #T a where ID>any(select ID from #T where Name=a.Name)
select * from #T
生成结果:
/*
ID          Name Memo
----------- ---- ----
1           A    A1
4           B    B1
(2 行受影响)
*/
--II、Name相同ID保留最大的一条记录:
方法1:
delete a from #T a where  exists(select 1 from #T where Name=a.Name and ID>a.ID)
方法2:
delete a  from #T a left join (select max(ID)ID,Name from #T group by Name) b on a.Name=b.Name and a.ID=b.ID where b.Id is null
方法3:
delete a from #T a where ID not in (select max(ID) from #T where Name=a.Name)
方法4(注:ID为唯一时可用):
delete a from #T a where ID not in(select max(ID)from #T group by Name)
方法5:
delete a from #T a where (select count(1) from #T where Name=a.Name and ID>a.ID)>0
方法6:
delete a from #T a where ID<>(select top 1 ID fr


相关文档:

SQL取出第 m 条到第 n 条记录的方法

从Table 表中取出第 m 条到第 n 条的记录:(Not In 版本)
SELECT TOP n-m+1 *
  from Table
  WHERE (id NOT IN (SELECT TOP m-1 id from Table ))
--从TABLE表中取出第m到n条记录 (Exists版本)
SELECT TOP n-m+1 * from TABLE AS a WHERE Not Exists
(Select * from (Select Top m-1 * from TABLE orde ......

SQL语句在JavaScript中的应用

最近一直在用javascript在做项目
可是做着做着
感觉很多功能代码都是重复的。
比如对javascript数组的排序
还有对数组数据的删选以及分组
所以,后来兴致以上来。
一发不可收拾。
写了一个能在javascript中应用的 SQL 库
后来又想,怎么不能用javascript直接连接数据库呢?
又做了一个javascript直连Sql数据的类库 ......

【转】关于"递归树形查询SQL"的好帖

-----------------------------------------------------------------------------------------------------------------------
create table tb(id varchar(3) , pid varchar(3) , name varchar(10))
insert into tb values('001' , null  , '广东省')
insert into tb values('002' , '001' , '广州市')
insert i ......

sql语言:如何判断字段是否存在,如何删除及创建字段

如何判断字段是否存在
 if col_length('表名','字段1') is null  ALTER TABLE 表名 ADD 字段1 Nvarchar(50)  if col_length('表名','字段2') is null  ALTER TABLE 表名 ADD 字段2 Nvarchar(50) ");
删除字段
if col_length('表名','字段1,') is not null  ALTER TABLE 表名 drop  c ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号