如何从SQL查询中删除以下数据中的交换列?

时间:2017-02-28 20:21:11

标签: sql postgresql swap

我使用以下SQL查询获取数据。

select * 
from 
    (select 
         c.cdr_id as cdr_id, 
         (select cdr_id 
          from coms_trnsfrmd.cdr_legacy 
          where cgs_cdr_id = k.assc_cdr_id) as associated_cdr_id 
     from 
         cgs_postgres.kl_cgs_associated_cdrs k 
     inner join 
         coms_trnsfrmd.cdr_legacy c on k.cdr_id = c.cgs_cdr_id )temp 
where 
    temp.associated_cdr_id is not null 
order by 
    temp.cdr_id

使用上面的sql查询,数据如下所示。

CDR_ID          ASSOCIATED_CDR_ID
123                 456
456                 123
123                 178
178                 123
156                 169
198                 456
456                 198

案例1:如果记录看起来像交换

CDR_ID    ASSOCIATED_CDR_ID
 123             456
 456             123

我不需要填充两者,我需要它第一个或第二个记录。

案例2:如果没有像

这样的交换记录
CDR_ID    ASSOCIATED_CDR_ID
156            169 

我需要它直接填充到目标中。

1 个答案:

答案 0 :(得分:0)

试试这个:

with your_table
as (
    select *
    from (
        select c.cdr_id as cdr_id,
            (
                select cdr_id
                from coms_trnsfrmd.cdr_legacy
                where cgs_cdr_id = k.assc_cdr_id
                ) as associated_cdr_id
        from cgs_postgres.kl_cgs_associated_cdrs k
        inner join coms_trnsfrmd.cdr_legacy c on k.cdr_id = c.cgs_cdr_id
        ) temp
    where temp.associated_cdr_id is not null
    )
----- The above is your original query. Actual solution is below.---- 


select *
from your_table
where CDR_ID <= ASSOCIATED_CDR_ID

union all

select *
from your_table t
where CDR_ID > ASSOCIATED_CDR_ID
    and not exists (
        select 1
        from your_table t2
        where t.CDR_ID = t2.ASSOCIATED_CDR_ID
            and t2.CDR_ID = t.ASSOCIATED_CDR_ID
        )

not exists确保没有两行具有可交换的值。