【问题标题】:Eliminate duplicate data消除重复数据
【发布时间】:2011-04-15 22:12:00
【问题描述】:

查询

SELECT
  ppc.personid,
  ppc.category,
  ppc.phonenumber,
  ppc.createts
FROM
  person_phone_contacts ppc
WHERE  
      CURRENT_TIMESTAMP BETWEEN ppc.createts AND ppc.endts
  AND CURRENT_DATE BETWEEN ppc.effectivedate AND ppc.enddate
ORDER BY
  ppc.personid, ppc.category, ppc.createts DESC

结果数据

3742 | Home   | xxx-xxx-xxxx | 2009-09-09 11:59:00.357-04
3742 | Home   | xxx-xxx-xxxx | 2009-08-04 20:13:17.161-04*
3742 | Mobile | xxx-xxx-xxxx | 2009-09-09 11:59:20.070-04
3742 | Mobile | xxx-xxx-xxxx | 2009-09-09 11:59:20.070-04*
3742 | Other  | xxx-xxx-xxxx | 2009-08-04 20:13:17.161-04

*要丢弃的重复项。

所需数据

3742 | Home   | xxx-xxx-xxxx | 2009-09-09 11:59:00.357-04
3742 | Mobile | xxx-xxx-xxxx | 2009-09-09 11:59:20.070-04
3742 | Other  | xxx-xxx-xxxx | 2009-08-04 20:13:17.161-04

问题

使用最近的日期(即使同一个人的同一类别中的多个电话号码具有相同的日期),检索每个人每个类别的单个电话号码的最有效方法是什么?

可能的解决方案

使用DISTINCT ON (ppc.category) category 可以限制每个人的结果,但是如何将其单独应用于所有人?

约束

  • PostgreSQL 8.3
  • 没有存储函数或过程

谢谢!

【问题讨论】:

  • 太糟糕了,你没有使用 8.4 w/窗口功能:-(
  • @Adam:是的,我希望我可以使用 8.4,但生产数据库是 8.3。
  • @Dave:那么小马的链接应该会有所帮助。那家伙知道什么?
  • 有升级的机会吗? v9 刚刚发布...数据集越小,时间越短。

标签: sql postgresql group-by distinct


【解决方案1】:

假设 (personid, category, createts) 是唯一的...

SELECT
  ppc.personid,
  ppc.category,
  ppc.phonenumber,
  ppc.createts
FROM
  person_phone_contacts AS ppc
  INNER JOIN (
    SELECT
      personid,
      category,
      MAX(createts) AS newest_createts
    FROM
      person_phone_contacts
    WHERE  
          CURRENT_TIMESTAMP BETWEEN createts AND endts
      AND CURRENT_DATE BETWEEN effectivedate AND enddate
    GROUP BY
      personid, category
  ) AS ppc2
  ON ppc.personid = ppc2.personid
    AND ppc.category = ppc2.category
    AND ppc.createts = ppc2.newest_createts

我不熟悉 Postgres 的 SQL 方言(我自己使用 MSSQL,这可以更优雅地解决),但由于这是非常标准的 SQL,我认为它应该可以工作。

【讨论】:

  • 不错。谢谢你。 8 秒内运行。
  • 对于“只有”100k 行的表,我认为这很慢 :) 如果您还没有关于 createts 的索引,请创建一个。可能会大大加快 JOIN,甚至可能是 WHERE 子句。
猜你喜欢
  • 1970-01-01
  • 2019-04-21
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多