sql - 如何在没有任何唯一标识符的情况下从查询中删除重复行
问题描述
我目前正在尝试更新包含大量重复行但不包含唯一标识符的表。我想在每个副本的 te_system_ref 之前添加一个减号 (-),但保留原件。我有以下查询,它为我提供了重复项的完整列表(如下所示),但我无法弄清楚我将如何只删除重复项。
当前查询:
select te_system_ref, te_event, te_Date
from ticket_events
where te_system_ref in (select te_system_ref from ticket_events
where te_event = 'VQ5 hard copy follows'
and te_date between '04/12/17' and '18/06/18 23:59:59'
group by te_system_ref
having count (te_event) > 4)
and te_event = 'VQ5 hard copy follows'
所以而不是:
1046338 2018-04-24 07:01:57.000 16210 VQ5 hard copy follows
1046338 2018-04-24 07:01:58.000 16210 VQ5 hard copy follows
1046338 2018-04-25 07:02:49.000 16210 VQ5 hard copy follows
1046338 2018-04-25 07:02:50.000 16210 VQ5 hard copy follows
1064317 2018-03-21 16:21:52.000 16210 VQ5 hard copy follows
1064317 2018-03-27 12:32:16.000 16210 VQ5 hard copy follows
1064317 2018-04-18 07:00:38.000 16210 VQ5 hard copy follows
1064317 2018-04-19 07:00:39.000 16210 VQ5 hard copy follows
1064351 2018-03-21 16:21:47.000 16210 VQ5 hard copy follows
1064351 2018-03-27 12:31:51.000 16210 VQ5 hard copy follows
1064351 2018-04-18 07:01:50.000 16210 VQ5 hard copy follows
1064351 2018-04-19 07:02:03.000 16210 VQ5 hard copy follows
我会得到:
1046338 2018-04-24 07:01:57.000 16210 VQ5 hard copy follows
1064317 2018-03-21 16:21:52.000 16210 VQ5 hard copy follows
1064351 2018-03-21 16:21:47.000 16210 VQ5 hard copy follows
任何帮助将不胜感激。
编辑:我已经找到了如下解决方案:
Update t set te_system_ref = ('-' + Convert(nvarchar(50),te_system_ref))
from (
select row_number() over (partition by te_system_ref order by (select 0)) as rn, te_system_ref, te_event from ticket_events where te_system_ref in
(
select te_system_ref from ticket_events where te_event = 'VQ5 hard copy follows' and te_date between '04/12/17' and '18/06/18 23:59:59' group by te_system_ref having count (te_event) > 10
)
and te_event = 'VQ5 hard copy follows'
)t
where t.rn <> 1 and te_system_ref not like '-%'
解决方案
你不能。
...但不包含唯一标识符...
好吧,在 SQL 中,所有具有相同值的行都是等效的。您无法区分看起来相同的两行,因此您不能只更新其中的一个。
您需要添加某种唯一键来标识每一行。可能是使用序列、时间戳或其他内容填充的额外列。如果你有这些,那么你可以开始区分行,你的生活会变得更容易。
推荐阅读
- c - 如何显示“预处理”代码忽略包含 GCC
- asp.net-core - 在 Asp.Net Core 中使用 Portable Objects (Orchard Core .po) 本地化 Display(Name=."..") 数据注释属性时出现问题
- php - 加载js文件失败
- julia - 关于 fft 函数
- linux - 如何重命名/移动文件并保留文件名的中间?我正在使用通配符来查找文件
- java - Import JavaFX 11 Maven project to Eclipse
- cplex - Docplex 与 CPLEX Python API
- java - 在预期之前执行的代码块代替布尔值
- sql - VS 2017 数据库项目,缺少触发器
- arrays - Angular:引导模式值第一次没有绑定