|AMNT1 | AMNT2 | Rank
__________________________
| 01 | 05 | rank1
| 05 | 10 | rank2
| 10 | 15 | rank3
___________________________
我需要case
语句,当它们之间的值之间时提供输出rank1,rank2,rank3
1 and 5
rank1,5 and 10
rank2等。
我有一个金额表,其中有deptid和金额
需要的输出是 需要从等级表中拉出等级的详细数量等级
如何编写select
查询并将其放在case
语句中?
它应该是动态的(我的意思是表值可以更改,但是我的case
语句应该读取最新值并提供输出)
答案 0 :(得分:1)
您不需要case
。您可以使用相关的子查询:
select (select rt.rank from ranktable rt where a.amount >= rt.amnt1 and a.amount < rt.amnt2) as ranking
from amount a;
您也可以以join
的身份进行此操作。
答案 1 :(得分:0)
您是否正在寻找以下案例陈述:
select * from (select case when input_amt>AMNT1 and input_amt<AMNT2 THEN rank end RANK
from ranktable) rnk
where rnk.RANK is not null
答案 2 :(得分:0)
这是一个联接版本,带有CTE中的示例数据:
with rankings (amnt1, amnt2, rank) as (
select 1, 5, 'rank1' from dual
union all select 5, 10, 'rank2' from dual
union all select 10, 15, 'rank3' from dual
),
amount (deptid, amount) as (
select 1, 0 from dual
union all select 2, 1 from dual
union all select 3, 4 from dual
union all select 4, 5 from dual
union all select 5, 6 from dual
union all select 6, 9 from dual
union all select 7, 10 from dual
union all select 8, 11 from dual
union all select 9, 15 from dual
union all select 10, 16 from dual
)
-- actual query
select a.deptid, a.amount, r.rank
from amount a
left join rankings r on a.amount >= r.amnt1 and a.amount < r.amnt2;
与Gordon的子查询方法得到的结果相同:
DEPTID AMOUNT RANK
---------- ---------- -----
1 0
2 1 rank1
3 4 rank1
4 5 rank2
5 6 rank2
6 9 rank2
7 10 rank3
8 11 rank3
9 15
10 16
如您所见,使用这些比较条件意味着没有匹配的15。您可以更改它们:
select a.deptid, a.amount, r.rank
from amount a
left join rankings r on a.amount > r.amnt1 and a.amount <= r.amnt2;
DEPTID AMOUNT RANK
---------- ---------- -----
1 0
2 1
3 4 rank1
4 5 rank1
5 6 rank2
6 9 rank2
7 10 rank2
8 11 rank3
9 15 rank3
10 16
但是现在没有1的匹配项。如果您尝试同时获得与between
相等的值:
select a.deptid, a.amount, r.rank
from amount a
left join rankings r on a.amount >= r.amnt1 and a.amount <= r.amnt2;
DEPTID AMOUNT RANK
---------- ---------- -----
1 0
2 1 rank1
3 4 rank1
4 5 rank1
4 5 rank2
5 6 rank2
6 9 rank2
7 10 rank2
7 10 rank3
8 11 rank3
9 15 rank3
10 16
由于行重叠,您现在获得多个结果。例如,当有多个比赛时,您可以保持“较高”排名来摆脱它们:
select a.deptid, a.amount,
max(r.rank) keep (dense_rank last order by r.amnt1) as rank
from amount a
left join rankings r on a.amount >= r.amnt1 and a.amount <= r.amnt2
group by a.deptid, a.amount;
DEPTID AMOUNT RANK
---------- ---------- -----
1 0
2 1 rank1
3 4 rank1
4 5 rank2
5 6 rank2
6 9 rank2
7 10 rank3
8 11 rank3
9 15 rank3
10 16
但是,实际上,您要么不应该重叠;或者您需要定义哪个结果正确。 (如果您的数据始终匹配某些内容,您甚至可能根本不需要/想要一个下限;但这也是一个稍微不同的查询。)