跨行的SQL DISTINCT值

时间:2019-06-12 08:39:10

标签: sql

我在各列中有重复的agreementnumber和有重复的telephone,并且我想获得唯一的agreementnumber,并且在列中有相应的唯一的telephone

我用SQL编写了查询,该查询为我提供了唯一的agreementnumber,但行中的telephone是重复的,但是我想要唯一的电话号码。

代码:

select agreementnumber,

  max(case when rn = 1 then telephone end) telephone1,

  max(case when rn = 2 then telephone end) telephone2,

  max(case when rn = 3 then telephone end) telephone3,

  max(case when rn = 4 then telephone end) telephone4,

  max(case when rn = 5 then telephone end) telephone5

from
(
  select agreementnumber, telephone,

    row_number() over(partition by agreementnumber order by telephone) rn
  from alternate_mobile 

) src
group by agreementnumber;

我想要以下输出。 col1和col2,col3,col4,col4中的唯一值。

col1 col2 col3 col4'' AGMTNO phone1 phone2 phone3

2 个答案:

答案 0 :(得分:1)

尝试在查询中进行以下更改:

select agreementnumber,
  max(case when rn = 1 then telephone end) telephone1,
  max(case when rn = 2 then telephone end) telephone2,   
  max(case when rn = 3 then telephone end) telephone3,
  max(case when rn = 4 then telephone end) telephone4,
  max(case when rn = 5 then telephone end) telephone5

from
(
  select x.*,
    row_number() over(partition by x.agreementnumber order by x.telephone) rn
  from (
    select distinct agreementnumber, telephone
    from alternate_mobile 
  ) x
) src
group by agreementnumber;

如果您获得重复的电话是因为您在agreementnumber表中重复了telephone / alternate_mobile

已编辑:

我更改查询以仅在电话中保留数字,删除所有其余字符:

select agreementnumber,
  max(case when rn = 1 then telephone end) telephone1,
  max(case when rn = 2 then telephone end) telephone2,   
  max(case when rn = 3 then telephone end) telephone3,
  max(case when rn = 4 then telephone end) telephone4,
  max(case when rn = 5 then telephone end) telephone5

from
(
  select x.*,
    row_number() over(partition by x.agreementnumber order by x.telephone) rn
  from (
    select distinct agreementnumber, regexp_replace(telephone,'[^0-9]', '') as telephone
    from alternate_mobile 
  ) x
) src
group by agreementnumber;

答案 1 :(得分:1)

请注意,您可以使用rank()代替row_number()来减少子查询的数量:

select agreementnumber,
       max(case when rn = 1 then telephone end) as telephone1,
       max(case when rn = 2 then telephone end) as telephone2,   
       max(case when rn = 3 then telephone end) as telephone3,
       max(case when rn = 4 then telephone end) as telephone4,
       max(case when rn = 5 then telephone end) as telephone5
from (select am.*,
             rank() over (partition by am.agreementnumber order by am.telephone) as rn
      from alternate_mobile am
     ) am
group by agreementnumber;
相关问题