【问题标题】:Need to delete multiply records from the table需要从表中删除多条记录
【发布时间】:2016-09-23 06:56:16
【问题描述】:

我有一个名为 TEST 的表

------------------------------------------  
ID  name          intime            
------------------------------------------      
1   ABC           2015-09-03 10:00:00       
1   ABC           2015-09-03 10:00:00       
2   XYZ           2015-09-03 11:00:00       
2   XYZ           2015-09-03 11:00:00       

我的目标是从表中删除重复的记录,例如 ABC intime is duplicate。而且我有多个记录,而不仅仅是 4 个,这只是一个例子。

我正在尝试这样的事情

with cte as 
(
select id,InTime ,count(*) as c
from intime as m
where InTime between convert(varchar(10),'2015-09-01 00:01:00',103) and convert(varchar(10),'2015-09-30 00:01:00',103)
group by id,InTime
having count(*) > 1
)
select * from cte
order by ID

输出

id  InTime                 c    
----------------------------------  
1   2015-09-03 10:00:00    2    
2   2015-09-03 11:00:00    2    

这个查询会给我在同一日期有多个intime的记录

with cte as 
(
select ID, inTime,
row_number() over (partition by convert(varchar(10),intime,103) order by intime desc) as r
from intime
where ID in (1)
and
inTime between '2015-09-01 00:01:00' and '2015-09-30 23:59:59'
)
select * from cte

delete  from cte
where r > 1

这是删除重复条目的查询。

我面临的问题是我必须手动输入 ID 1 到 1,如果我在 (1,2) 中执行 ID 的操作

它给我的输出是:

ID  inTime              r   
2   2015-09-03 11:00:00 1   
2   2015-09-03 11:00:00 2   
1   2015-09-03 10:00:00 3   
1   2015-09-03 10:00:00 4   

然后如果我删除 r>1 它将删除 3 行。

我想创建一个可以从表中删除所有重复记录的东西。我正在使用 sql-2008。任何建议都会有所帮助。

【问题讨论】:

  • 我在查询中使用 row_number

标签: sql sql-server-2008


【解决方案1】:

试试这个

with abc as
  (
  select * ,rn=ROW_NUMBER()over(partition by ID ,name,intime order by columnName)from yourtablename
  )

  delete from abc where rn>1 

【讨论】:

    【解决方案2】:

    为什么不使用 DISTINCT 将数据复制到新表中?

    -- 复制... select DISTINCT * into tmp_yourtablename from yourtablename

    -- 删除原始数据 截断表你的表名

    --重新加载它们... insert yourtablename select * from tmp_yourtablename

    -- 完成后删除 tmp_yourtablename...

    【讨论】:

      猜你喜欢
      • 2011-03-11
      • 2013-01-30
      • 2010-12-27
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 2023-02-25
      相关资源
      最近更新 更多