【问题标题】:SQL - remove rows with more than one unique date against IDSQL - 根据 ID 删除具有多个唯一日期的行
【发布时间】:2012-10-29 23:46:40
【问题描述】:

我试图只保留 ID 具有单个销售日期的行,例如。

ID SALES_DTE
101 2012 年 1 月 10 日
101 12 年 1 月 10 日
101 12 年 1 月 10 日
102 12 年 1 月 10 日
102 12 年 1 月 13 日
103 12 年 1 月 13 日

在上面,我想保留 ID 101 和 103,因为它们只有一个销售日期。但我不想要 102,因为它有两个销售日期。有人可以帮忙吗?

【问题讨论】:

  • select * from mytable tb where not exists (select * from mytable nx where nx.id =tb.id and nx.sales_date <> tb.sales_date); NB 如果你想物理删除它们:将“select *”替换为“delete”并删除 NOT

标签: sql


【解决方案1】:
delete from your_table
where id not in 
(
   select id
   from your_table
   group by id
   having count(distinct sales_date) = 1
)

【讨论】:

  • 注意:这也会删除碰巧有 sales_date IS NULL 的元组这可能是也可能不是 OP 的意图。
  • 这可以通过having 子句进行更改:having count(distinct sales_date) <= 1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 2021-09-21
  • 1970-01-01
  • 2022-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多