如何解决Oracle SQL,如果值适用于不同情况,则分配名称
我遇到了无法解决的问题。
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' 中,我想分配一个值 'Good' 如果数据在 '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
解决方法
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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。