如果满足条件,则计算为不重复

时间:2020-08-31 16:36:17

标签: sql oracle count average distinct

我有一张表,显示address_no是否有电话。要确定,我正在查看cell_phone和house_phone列,并且只想在house_phone和cell_phone为null时才写“ no phone”。

每个address_no都有居住在该地址的人的记录。如果至少一个人拥有电话,或者house_phone不为null,则该address_no具有电话,否则address_no没有电话信息。

ADDRESS_NO------PERSON_ID------CELL_PHONE-------HOUSE_PHONE
11111-----------11-------------111000----------------------  
11111-----------12-------------122000----------------------
11111-----------13----------------------------------1313000
22222-----------21----------------------------------2121000
33333-----------31-----------------------------------------
33333-----------32-----------------------------------------
44444-----------41-------------411000---------------4141000
55555-----------51-------------511000----------------------
55555-----------52-----------------------------------------
55555-----------53-----------------------------------------

如上所示,我希望得到5个具有电话信息的地址中的4个。

如何编写sql查询以在oracle sql中找到编号

2 个答案:

答案 0 :(得分:0)

您可以使用聚合和case表达式:

select address_id,
       (case when max(cell_phone) is null and max(house_phone) is null
             then 'No Phone' else 'Phone'
        end) as phone_flag
from t
group by address_id;

答案 1 :(得分:0)

如果要列出具有电话信息的地址,则可以使用having子句过滤数据集:

select address_no
from mytable
group by address_no
having coalesce(max(cell_phone), max(house_phone)) is not null

另一方面,如果要计算包含电话信息的地址的总比例,则可以使用两种聚合级别:

select avg(case when phone_no is null then 0 else 1 end) ratio
from (
    select coalesce(max(cell_phone), max(house_phone)) phone_no
    from mytable
    group by address_no
) t