如何删除来自 SQL 查询的以下数据中的交换列?
How to remove swap columns in below data getting from SQL query?
我正在使用以下 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:如果没有像
这样的swap记录
CDR_ID ASSOCIATED_CDR_ID
156 169
我需要它直接填充到目标中。
试试这个:
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
确保没有两行具有可交换的值。
我正在使用以下 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:如果没有像
这样的swap记录CDR_ID ASSOCIATED_CDR_ID
156 169
我需要它直接填充到目标中。
试试这个:
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
确保没有两行具有可交换的值。