【问题标题】:1 table, many columns, one column of duplicates, remove duplicates1表,多列,一列重复,去除重复
【发布时间】:2020-03-11 03:42:24
【问题描述】:

我有一个表,其中有超过 30 列需要查询,其中一列有重复条目。如何查询表并按一列区分而不列出要在选择中显示的每一列。
例如 -

Select * 
from Event
where subject_ID = 49
and date between '01-NOV-2019' and '14-NOV-2019'

这会显示 100 行,但应该只有 50 行,并且 case_id 列是区分重复项的唯一列。我需要查看表中的所有列,但不希望出现重复的 case_id 行,并且真的不想列出选择中的所有列。

试过

select distinct case_id, * 
from event
where subject_ID = 49
and date between '01-NOV-2019' and '14-NOV-2019'

没用。

我应该澄清一下,每隔一行都是重复的。每组数据有 2 行,case_id 是唯一区分重复项的数据。有没有办法说只显示奇数行?

【问题讨论】:

  • 选择不同的 * 不起作用?
  • 造成重复的原因是您的 *
  • 用您正在使用的数据库标记您的问题。
  • 这个问题有点道理。这听起来像是使用窗口函数对分区 case_id 中的记录进行排序的典型用法。然后从每个分区中取出顶部的一个。

标签: sql duplicates distinct


【解决方案1】:

导致您的distinct 是您的*,您可以使用row_number()partition by case_id 来获取topcase_id

select * from 
    (Select row_number() over (partition by case_id order by case_id) rn, * from Event 
        where subject_ID = 49 and date between '01-NOV-2019' and '14-NOV-2019'
    ) t1 
where t1.rn = 1

【讨论】:

  • 我应该指定我正在使用 Oracle SQL,所以我切换到 rownum 并不断收到“未找到关键字”
【解决方案2】:

如果您有一列并且希望每个值有一行,您可以使用row_number()。在下面的代码中,case_id就是这个列:

Select *
from (select e.*,
             row_number() over (partition by case_id order by case_id) as seqnum
      from Event e
      where subject_ID = 49 and date between '01-NOV-2019' and '14-NOV-2019'
     ) e
where seqnum = 1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 2020-09-14
    • 2015-10-17
    • 2017-12-15
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    相关资源
    最近更新 更多