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

rqdpfwrv  于 2023-04-20  发布在  Oracle
关注(0)|答案(2)|浏览(111)

我在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

我想不通这个结果是真是假

6qqygrtg

6qqygrtg1#

也许按(公司和日期)按(源)排序行,以便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>
huwehgph

huwehgph2#

如果我正确理解了你的问题,那么你需要所有具有source的最小值的行来对应company

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

如果你只想要那些,其中source是最小的,但是0102你可以添加条件:

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')

相关问题