首页 > 解决方案 > 从 SQL 中的列中删除重复值

问题描述

我有两个表A( group_id, id, subject) 和B( id, date)。下面是表A和B在id上的联表。我尝试使用 distinct 和 partition 仅删除 group_id(field) 中的重复项,但没有运气:

在此处输入图像描述

我的代码:

select 
    a.group_id, a.id, a.subject, b.date 
from
    A a 
inner join
    (select 
         b.*, 
         row_number() over (partition by group_id order by date asc) as seqnum
     from 
         B b) b on a.id = b.id and seqnum = 1
order by
    date desc; 

运行代码时出现此错误:

在第 1 行的 'partition by group_id order by date asc) as seqnum from B' 附近的查询中不能单独使用分区

这是我的预期结果:

我的预期结果:

先感谢您!

标签: sqldatabasepartition

解决方案


看起来您想要显示的表格中每一行的最早日期。您的问题提到了两张表,但您只显示了一张。

我建议在大多数数据库中使用相关子查询:

select b.*
from b
where b.date = (select min(b2.date)
                from b b2
                where b2.group_id = b.group_id
               );

我懂了。你需要join先然后使用row_number()

select ab.*
from (select a.group_id, a.id, a.subject, b.date,
             row_number() over (partition by a.group_id order by b.date) as seqnum
      from A a join
           B b
           on a.id = b.id
     ) ab
where seqnum = 1
order by date desc; 

推荐阅读