sql只加入一次

xeufq47z  于 2021-07-29  发布在  Java
关注(0)|答案(3)|浏览(267)

我有以下情况
表1

Id          Sum
1           100
2           100
3           200
4           400

表2

ID          Sum
5           100
6           200
7           300
8           400

我想写一个连接两个表的查询,只显示一次匹配的结果。结果应该是

1     100     Match
2     100     Mismatch 
3     200     Match
4     300     Mismatch 
5     400     Match

我正在使用此查询

select a.id, a.sum,b.id,b.sum,
CASE 
    when a.sum = b.sum then 'Match' 
    else 'Mismatch' 
end as Result 
from table1 a  LEFT OUTER join table2 b on a.sum = b.sum

结果是

1     100    5     100     Match
    2     100    5     100     Match
    3     200    6     200     Match
    4     400    8     400     Match

基本上,这是一个收集系统。系统自动将数据保存在表2中。当员工进行真正的收集时,他们上传表1中的数据。现在我想展示一个报表,它显示基于总和的集合之间的差异。所以,如果employee插入了100$2次,我应该显示系统只捕获了一次,并且在表1中有一个额外的行

umuewwlo

umuewwlo1#

因为您想突出显示两个表之间的差异。你应该按总和分组并比较总和的连续性。使用完全外部连接,因为您希望显示两侧的差异,如下所示:

select *,
CASE 
when a.cnt = b.cnt then 'Match' 
else 'Mismatch' 
end as Result from
(select sum,count(1) as cnt from table1 group by sum) a
full join
(select sum,count(1) as cnt from table2 group by sum) b
on a.sum=b.sum

sql fiddle演示
输出如下所示:

z9smfwbn

z9smfwbn2#

试试这个

select t1.id, t1.sum,
    CASE 
        when t1.sum = t2.sum then 'Match' 
        else 'Mismatch' 
    end
    as Compare
    from table1 t1 
    inner join table2 t2 on t1.id = t2.id
tv6aics1

tv6aics13#

你想加入吗 id ?

select 
    t1.id, 
    t1.sum, 
    case when t1.sum = t2.sum then 'Match' else 'Mismatch' end as result
from table1 t1
inner join table2 t2 on t2.id = t1.id

或者,如果 id 我们不做数学,你可能想用 row_number() :

select 
    t1.id id1, 
    t1.sum sum1, 
    t2.id id2,
    t2.sum sum2,
    case when t1.sum = t2.sum then 'Match' else 'Mismatch' end as result
from (select t1.*, row_number() over(order by id) rn from table1 t1) t1
inner join ((select t2.*, row_number() over(order by id) rn from table2 t2) t2 
    on t2.rn = t1.rn

最后:如果两个表中的行数可能不同,请使用 full join 而不是 inner join (如果数据库支持):

select 
    t1.id id1, 
    t1.sum sum1, 
    t2.id id2,
    t2.sum sum2,
    case when t1.sum = t2.sum then 'Match' else 'Mismatch' end as result
from (select t1.*, row_number() over(order by id) rn from table1 t1) t1
full join (select t2.*, row_number() over(order by id) rn from table2 t2) t2 
    on t2.rn = t1.rn

相关问题