【问题标题】:SQL Server keep only oneSQL Server 只保留一个
【发布时间】:2022-06-21 16:23:34
【问题描述】:

我正在使用 SQL Server 2008R2 并有一个表 (TableA),用于保存特定日期、时间段和房间的酒店功能之间的冲突。

问题在于它显示了两次,意思是发现 FunctionA 在某些方面与 FunctionB 冲突,然后显示 FunctionB 冲突FunctionA

的方法相同
orig_id conflicting_id  event_name  conflict_name   on_date     room_id time_from   time_to conflict_from   conflict_to
22108   22255           FunctionA   FunctionB       15/06/2022  9       07:00       09:30   07:00           09:30
22108   22255           FunctionA   FunctionB       15/06/2022  9       12:30       13:30   12:30           13:30
22108   22255           FunctionA   FunctionB       15/06/2022  30      09:00       17:30   09:00           17:30
22108   22255           FunctionA   FunctionB       15/06/2022  31      09:00       17:30   09:00           17:30
22108   22255           FunctionA   FunctionB       15/06/2022  32      09:00       17:30   09:00           17:30
22255   22108           FunctionB   FunctionA       15/06/2022  9       07:00       09:30   07:00           09:30
22255   22108           FunctionB   FunctionA       15/06/2022  9       12:30       13:30   12:30           13:30
22255   22108           FunctionB   FunctionA       15/06/2022  30      09:00       17:30   09:00           17:30
22255   22108           FunctionB   FunctionA       15/06/2022  31      09:00       17:30   09:00           17:30
22255   22108           FunctionB   FunctionA       15/06/2022  32      09:00       17:30   09:00           17:30

在上述情况下,FunctionAFunctionBon_date,room_id,conflict_from,conflict_to 发生冲突 并且 FunctionB相同标准上与 FunctionA 冲突。

我怎样才能只保留一个冲突集?

【问题讨论】:

  • 2008 R2 已经停产几年了。仍然使用它是危险和不负责任的。迁移到受支持的版本是第 1 项工作。

标签: sql sql-server duplicates


【解决方案1】:

您要删除存在重复项的行。因此,请使用EXISTS 查找具有相同条件但切换了事件 ID 或名称的行。最后,为了不删除两行,决定一个,例如orig_id 大于conflicting_id 的那个(因此将行保持在原来的位置,反之亦然)。

delete from conflicts
where exists
(
  select null
  from conflicts same
  where -- same criteria
        same.on_date = conflicts.on_date
    and same.room_id = conflicts.room_id
    and same.time_from = conflicts.time_from
    and same.time_to = conflicts.time_to
    -- but switched IDs
    and same.orig_id = conflicts.conflicting_id
    and same.conflicting_id = conflicts.orig_id
)
and orig_id > conflicting_id;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 2011-03-29
    相关资源
    最近更新 更多