如何选择具有特定值的记录(如果没有),然后在SQL中使用不同的值?
我想从一个表中选择一些记录,其中phone_type='PR'如果记录没有phone_type='PR',则使用'CL' 表:如何选择具有特定值的记录(如果没有),然后在SQL中使用不同的值?,sql,oracle,oracle-sqldeveloper,Sql,Oracle,Oracle Sqldeveloper,我想从一个表中选择一些记录,其中phone_type='PR'如果记录没有phone_type='PR',则使用'CL' 表: ID NAME Phone_Type Phone_Number 1 Austin PR 789-100-1000 1 Austin CL 762-100-1009 1 Austin PA 789-100-1000 2 Andrew PR 565-100-1000 2 Andrew
ID NAME Phone_Type Phone_Number
1 Austin PR 789-100-1000
1 Austin CL 762-100-1009
1 Austin PA 789-100-1000
2 Andrew PR 565-100-1000
2 Andrew CL 312-199-6754
2 Andrew FA 602-100-1000
3 Kathy CL 100-100-1000
3 Kathy PA 105-109-1002
结果应该是这样的:
ID NAME Phone_Type Phone_Number
1 Austin PR 789-100-1000
2 Andrew PR 565-100-1000
3 Kathy CL 100-100-1000
我尝试过的SQL代码之一:
select id, name,phone_number_combined,case when phone_type = 'CL' then phone_number_combined end
from telephone where phone_type = 'PR'
我不知道如何在SQL中实现这一点,因为我已经尝试过CASE语句,exists,甚至尝试过将表本身连接起来。使用函数
-- Oracle
with s (id, name, phone_type, phone_number) as (
select 1, 'Austin', 'PR', '789-100-1000' from dual union all
select 1, 'Austin', 'CL', '762-100-1009' from dual union all
select 2, 'Andrew', 'PR', '565-100-1000' from dual union all
select 2, 'Andrew', 'CL', '312-199-6754' from dual union all
select 3, 'Kathy' , 'CL', '100-100-1000' from dual)
select id, name, phone_type, phone_number
from
(select
id, name, phone_type, phone_number,
row_number() over (partition by id order by phone_type desc) rn
from s
)
where rn = 1;
ID NAME PHONE_TYPE PHONE_NUMBER
---------- ------ ---------- ------------
1 Austin PR 789-100-1000
2 Andrew PR 565-100-1000
3 Kathy CL 100-100-1000
3 rows selected.
您应该使用
分组依据
和合并
:
WITH telephone (id, name, phone_type, phone_number) AS
( SELECT * FROM (VALUES
( 1, 'Austin', 'PR', '789-100-1000'),
( 1, 'Austin', 'CL', '762-100-1009'),
( 2, 'Andrew', 'PR', '565-100-1000'),
( 2, 'Andrew', 'CL', '312-199-6754'),
( 3, 'Kathy' , 'CL', '100-100-1000') ))
select
id as ID,
name as NAME,
COALESCE( max(case when phone_type = 'PR' then 'PR' end),
max(case when phone_type = 'CL' then 'CL' end) ) as PHONE_TYPE,
COALESCE( max(case when phone_type = 'PR' then phone_number end),
max(case when phone_type = 'CL' then phone_number end) ) as PHONE_NUMBER
from telephone
group by id, name
order by id, name
----
Results
ID NAME PHONE_TYPE PHONE_NUMBER
1 Austin PR 789-100-1000
2 Andrew PR 565-100-1000
3 Kathy CL 100-100-1000
如果表中有1000多条记录,并且还包括电话类型(FA和PA),该怎么办。上述查询是否仍然有效@NBK如果还有足总,你希望得到什么样的结果?如果你发布了一个不完整的问题,不要期望得到一个完美的答案。下定决心。你为什么一开始不说英足总和英足总?您需要使用decode或case表达式修改我的查询的order by子句。@Littlefoot我不想发布整个问题,因为它包含太多带有其他指示符的多个值。我并不指望我的整个问题都能得到完美的答案。我只是想知道我可以用什么来解决这个简单的问题,然后我就可以修改了。@akk0rd87非常感谢您的快速回复。我完全忘记了行数函数。