【问题标题】:Return duplicated rows by max column按最大列返回重复的行
【发布时间】:2019-03-19 13:34:34
【问题描述】:

我正在尝试按最大 initID 复制所有行(标题)。

这是我的桌子:

  ID |      title      | revision | initID
  1  |    Mytitle 1    |    0     |  10
  2  |    Mytitle 1    |    1     |  10
  3  |    Mytitle 1    |    2     |  10
  4  |    Mytitle 1    |    0     |  20
  5  |    Mytitle 1    |    1     |  20

  6  |    Mytitle 2    |    0     |  30
  7  |    Mytitle 2    |    1     |  30

  8  |    Mytitle 3    |    0     |  40
  9  |    Mytitle 3    |    1     |  40
  10 |    Mytitle 3    |    0     |  50
  11 |    Mytitle 3    |    1     |  50
  12 |    Mytitle 3    |    2     |  50

  13 |    Mytitle 4    |    0     |  60

我的目标是检查是否有多个 initID 具有相同的标题并使用 MAX(initid) 获取重复的行。

例如,我想从我的请求中得到这个回报:

  4  |    Mytitle 1    |    0     |  20
  5  |    Mytitle 1    |    1     |  20
  10 |    Mytitle 3    |    0     |  50
  11 |    Mytitle 3    |    1     |  50
  12 |    Mytitle 3    |    2     |  50

如果标题只有一个 initID,我不想恢复这些行。

【问题讨论】:

  • 标记您正在使用的 DBMS。

标签: sql postgresql aggregate-functions


【解决方案1】:

您可以将EXISTS 与相关子查询一起使用:

SELECT t.*
FROM table t
WHERE EXISTS (SELECT 1 FROM table t1 WHERE t.title = t1.title AND t1.initID <> t.initID) AND
      t.initID = (SELECT MAX(t1.initID) FROM table t1 WHERE t1.title  = t.title);

【讨论】:

    【解决方案2】:

    使用相关子查询

     select t.* from table_name t
     where exists( select 1 from table_name t2 where t1.title=t2.title 
                       having count(*)>1)
     and t1.initID=( select max(initID) from table_name t2 where t1.title=t2.title)
    

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 2012-05-07
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 2016-08-24
      • 2020-04-15
      相关资源
      最近更新 更多