首页 > 解决方案 > 查找 2 个相似表之间的差异(计数差异)

问题描述

我有 2 个类似的表,一个是每月更新的实时表,另一个是相同的数据,但有一个snapshot表,如显示特定数据时的数据,还有一个额外的列Live_History_Month调用确定数据进来的month_year。

我正在尝试查看特定列的计数是否有任何变化,以便我可以进一步调查。我创建了以下 SQL 代码

select codetoinvestigate
,Year_Month
,count(*)
from tbl1
where Live_History_Month = Year_Month
group by codetoinvestigate
,Year_Month


select codetoinvestigate
,Year_Month
,count(*)
from tbl2
group by codetoinvestigate
,Year_Month

现在我如何链接这些,以便我可以查看指定列的计数之间是否有任何差异,以便我可以做出需要调查的明智决定。

只是为了确认 tbl1 是快照表,而 tbl2 是当前最新数据的表。

谢谢

标签: sqlsql-servertsql

解决方案


这将返回不同的计数和缺失的代码

with t1 as
 (
    select codetoinvestigate
    ,Year_Month
    ,count(*) as cnt
    from tbl1
    where Live_History_Month = Year_Month
    group by codetoinvestigate
    ,Year_Month
 ),
t2 as
 (
    select codetoinvestigate
    ,Year_Month
    ,count(*) as cnt
    from tbl2
    group by codetoinvestigate
    ,Year_Month
 )

select coalesce(t1.codetoinvestigate,  t2.codetoinvestigate)
   ,coalesce(t1.Year_Month, t2.Year_Month)
   ,t1.cnt
   ,t2.cnt
   ,case when t1.codetoinvestigate is null 
           then 'missing code t1'
          when t2.codetoinvestigate is null 
            then 'missing code t2'
          when t1.cnt <> t2.cnt 
            then 'count different'
        etc...
    end
from t1 full join t2
  on t1.codetoinvestigate = t2.codetoinvestigate
 and t1.Year_Month = t2.Year_Month
 and t1.cnt <> t2.cnt

要仅检查不同的计数,请切换到内部联接


推荐阅读