【问题标题】:Update table in rows which are partial duplicates在部分重复的行中更新表
【发布时间】:2014-02-27 04:45:39
【问题描述】:

我的数据集包含来自不同行业的不同公司的每日(实际上是工作日)时间序列,我使用 PostgreSQL。我的数据集中有一个指标变量,取值为 1、-1,大多数情况下为 0。为了更好地理解问题,我将给定公司的指标变量不等于 0 的情况称为指标事件。

如果某一天某一行业有多个指标事件,则相关公司的指标变量应更新为0。

我们可以想到以下示例数据集:

day              company     indicator     industry
2012-01-12       A           1             financial
2012-01-12       B           1             consumer
2012-01-12       C           0             consumer
2012-01-13       A           0             financial
2012-01-13       B           1             consumer
2012-01-13       C           0             consumer
2012-01-16       A           1             financial
2012-01-16       B           -1            consumer
2012-01-16       C           1             consumer

所以要更新为零的指标值是2012-01-16的B公司和C公司的条目,因为它们都来自同一行业并且在同一天经历了指标事件。

我的想法是使用 exists 运算符:

    update mytable t1 set indicator = 0
    where exists (
              select 1
              from mytable t2
              where t2.day = t1.day
              and t2.industry = t1.industry
              and t2.indicator <> 0
              and t1.indicator <> 0)

但不知何故,将所有指标值更新为 0,我不知道为什么。

您有什么想法可以解决这个问题,或者如何用另一种方法解决我的问题?

【问题讨论】:

  • 如果 { day, company, industry } 都相同,您是否有额外的关键字段(例如“id”)来区分记录?
  • @wildplasser 不,但我也想过这个问题。我可以用 CREATE SEQUENCE id_seq 添加它; ALTER TABLE mytable ADD id INT UNIQUE; ALTER TABLE mytable ALTER COLUMN id SET DEFAULT NEXTVAL ('id_seq'); UPDATE TABLE mytable SET id = NEXTVAL ('id_seq'); ALTER TABLE mytable 添加主键(id)
  • @wildplasser 但是你问的不可能发生,因为组合(天,公司)总是不同的
  • 在这种情况下,@erikxiv 的解决方案就足够了。

标签: sql postgresql


【解决方案1】:

您可能想要添加一个条件以不将行加入自身(这将始终为真),例如

update mytable t1 set indicator = 0
where exists (
          select 1
          from mytable t2
          where t2.day = t1.day
          and t1.company <> t2.company
          and t2.industry = t1.industry
          and t2.indicator <> 0
          and t1.indicator <> 0)

【讨论】:

  • 是的,这正是我们所缺少的。非常感谢您的回答! @erikxiv
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 1970-01-01
  • 2022-01-01
  • 2023-03-31
  • 2017-12-22
相关资源
最近更新 更多