【问题标题】:Oracle SQL, assigning names if value holds true for different casesOracle SQL,如果值对不同情况成立,则分配名称
【发布时间】:2021-03-24 06:09:58
【问题描述】:

我遇到了无法解决的问题。

with t as (
select 'Apple' a, 2016 yr from dual
union all select 'Tesla' a, 2016 yr from dual
union all select 'Microsoft' a, 2016 yr from dual
union all select 'Google' a, 2016 yr from dual
union all select 'Apple' a, 2017 yr from dual
union all select 'Google' a, 2017 yr from dual
union all select 'Apple' a, 2018 yr from dual
union all select 'Amazon' a, 2018 yr from dual
union all select 'Tesla' a, 2018 yr from dual
union all select 'Nvdia' a, 2018 yr from dual
)

select * from t;

如果数据在所有 3 年的“a”列中都存在,我想分配一个值“好” 如果数据在“a”列中存在 2 年任意组合(2016 年、2017 年)或(2017 年、2018 年)或(2016 年、2018 年),则分配值“平均” 如果数据在“a”列中仅存在 1 年(2016 年)或(2017 年)或(2018 年),则分配值“坏”

期望的输出:

我试过(Case)方法,好像不行。

这里的 SQL FIDDLE UK https://dbfiddle.uk/?rdbms=oracle_18&fiddle=7eda42b2658ee571f7a2e66fd57c0c09

【问题讨论】:

    标签: sql oracle plsql case


    【解决方案1】:

    count 的解析形式可能会有所帮助。

    SQL> with t as (
      2  select 'Apple' a, 2016 yr from dual
      3  union all select 'Tesla' a, 2016 yr from dual
      4  union all select 'Microsoft' a, 2016 yr from dual
      5  union all select 'Google' a, 2016 yr from dual
      6  union all select 'Apple' a, 2017 yr from dual
      7  union all select 'Google' a, 2017 yr from dual
      8  union all select 'Apple' a, 2018 yr from dual
      9  union all select 'Amazon' a, 2018 yr from dual
     10  union all select 'Tesla' a, 2018 yr from dual
     11  union all select 'Nvdia' a, 2018 yr from dual
     12  )
     13  select a, yr,
     14    case when count(*) over (partition by a) = 3 then 'good'
     15         when count(*) over (partition by a) = 2 then 'average'
     16         when count(*) over (partition by a) = 1 then 'bad'
     17    end res
     18  From t
     19  order by yr, a;
    
    A                 YR RES
    --------- ---------- -------
    Apple           2016 good
    Google          2016 average
    Microsoft       2016 bad
    Tesla           2016 average
    Apple           2017 good
    Google          2017 average
    Amazon          2018 bad
    Apple           2018 good
    Nvdia           2018 bad
    Tesla           2018 average
    
    10 rows selected.
    
    SQL>
    

    【讨论】:

    • 谢谢,@Littlefoot 我以为我必须使用解码。不知道 count(*) 技术。
    猜你喜欢
    • 2012-08-31
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多