SQL:在重复时尝试选择一个选项作为默认选项(oracle)

问题描述 投票:0回答:2

我在 SQL 中遇到了一些问题

我的数据是这样的

公司 报告日期 来源
01 20071231 01
01 20081231 01
01 20081231 02
02 20071231 02
02 20081231 02
03 20071231 01
03 20071231 02

我想在源列中选择“01”作为默认值。但如果没有,那么我想选择源'02'

我想要的结果是这样的

公司 报告日期 来源
01 20071231 01
01 20081231 01
02 20071231 02
02 20081231 02
03 20071231 01

谢谢

select company
     , report date
     , source
from   (
        select *,
         count(*) over
           (partition by company, report date, source) as b
from the table
where b > 1

我不知道这个结果是真是假

oracle duplicates default-value
2个回答
0
投票

如果我正确理解你的问题,那么你需要所有具有最小值的行

source
相应
company
.

select
    company,
    "report date",
    source
from
    mytable t1
where
    source = (
        select min(source)
        from mytable t2
        where t1.company = t2.company
    )

如果你只想要那些,其中

source
是最小的,但是无论是
01
还是
02
你都可以添加条件:

select
    company,
    report_date,
    source
from
    mytable t1
where
    source = (
        select min(source)
        from mytable t2
        where t1.company = t2.company
    )
and source in ('01', '02')

0
投票

也许按(来源)对每个(公司和日期)的行进行排序,以便 01(如果存在)出现在 02 或任何其他值之前,然后提取排名最高的行?

样本数据:

SQL> with test (company, report_date, source) as
  2    (select '01', 20071231, '01' from dual union all
  3     select '01', 20081231, '01' from dual union all
  4     select '01', 20081231, '02' from dual union all
  5     select '02', 20071231, '02' from dual union all
  6     select '02', 20081231, '02' from dual union all
  7     select '03', 20071231, '01' from dual union all
  8     select '03', 20071231, '02' from dual
  9    ),

查询从这里开始:

 10  temp as
 11    (select company, report_date, source,
 12       row_number() over (partition by company, report_date order by source) rn
 13     from test
 14    )
 15  select company, report_date, source
 16  from temp
 17  where rn = 1;

COMPANY    REPORT_DATE SOURCE
---------- ----------- ----------
01            20071231 01
01            20081231 01
02            20071231 02
02            20081231 02
03            20071231 01

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.