您应该使用正确的连接语法。特别是,为此,您应该使用full outer join
,因为文档可能在一个或另一个表中没有记录。
其次,因为你不想计算重复,你需要计算一些东西。以下假设id
每个表中都有一列(某种):
Select coalesce(s.DocumentNumber, s2.DocumentNumber) as DocumentNumber,
Count(distinct s.id), Count(distinct s2.id)
From Sheet s full outer join
Sheet2 s2
on s.DocumentNumber = s2.DocumentNumber
group by coalesce(s.DocumentNumber, s2.DocumentNumber);
如果您没有id
列,或者您的数据库不支持full outer join
,则以下内容也可以使用:
select DocumentNumber, max(cnt_s) as cnt_s, max(cnt_s2) as cnt_s2
from ((select DocumentNumber, count(*) as cnt_s, 0 as cnt_s2
from Sheet s
group by DocumentNumber
) union all
(select DocumentNumber, 0, count(*) as cnt_s2
from Sheet2 s2
group by DocumentNumber
)
) t
group by DocumentNumber;
编辑:
这种union all
方法实际上更适合价格:
select DocumentNumber, max(cnt_s) as cnt_s, max(cnt_s2) as cnt_s2,
max(price_s) - max(price_s2)
from ((select DocumentNumber, count(*) as cnt_s, 0 as cnt_s2,
sum(price) as price_s, 0 as price_s2
from Sheet s
group by DocumentNumber
) union all
(select DocumentNumber, 0, count(*) as cnt_s2,
0, sum(price) as price_s2
from Sheet2 s2
group by DocumentNumber
)
) t
group by DocumentNumber;
注意:此版本将缺失的价格视为 0。对于这种情况,您可能需要替换0
为NULL
。