如何从一个来源提取一组记录,并从另一个来源提取其余记录

时间:2019-01-31 22:39:25

标签: sql

我必须检索具有source_name ='health'和'health_details'的记录。

“健康详细信息”有100条记录,但“健康”具有有限的记录(例如10条)(这10条记录也存在于health_details中)。

现在,我必须从'health'中检索所有10条记录,并从'health_details'中排除这10条记录,并从'health_details'中检索其余90条记录。到目前为止,我从一个庞大的查询中获得了以下子查询。

select case
         when source_name = 'health_details' then cust_number
         when source_name != 'health_details' and source_name = 'health' then cust_number
       end as "custnumber"
from table a

2 个答案:

答案 0 :(得分:0)

尝试一下,您可能有一些用于比较记录的标识符。为此,我做了descr专栏。

CREATE TABLE a (
  descr varchar(20),
  source_name varchar(20),
  cust_number int
);
INSERT INTO a (descr, source_name,cust_number) VALUES ('abc', 'health_details',25);
INSERT INTO a (descr, source_name,cust_number) VALUES ('xyz' ,'health_details',225);
INSERT INTO a (descr, source_name,cust_number) VALUES ('abc', 'health', 10);
select * from a 
where source_name = 'health'
union 
select * from a 
where source_name = 'health_details' and 
descr not in (
  select aa.descr from a as aa where aa.source_name = 'health'
)

结果是两个记录:

descr   source_name cust_number
abc health  10
xyz health_details  225

答案 1 :(得分:0)

这是一个优先级查询。通用方法使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by cust_number
                                order by (case when source = 'health' then 1 else 2 end)
                               ) as seqnum
      from t
      where source in ('health', 'health_details')
     ) t
where seqnum = 1;

以上内容适用于许多来源。对于{两个},not exists / union all很方便:

select t.*
from t
where t.source = 'health'
union all
select t.*
from t
where t.source = 'health_details' and
      not exists (select 1
                  from t t2
                  where t2.cust_number = t.cust_number and
                        t2.source = 'health'
                 );