比较两个 SQL 个表和 return 个有更改的行数

Compare two SQL tables and return count of rows with changes

我有两个来自 SQL table 的分区,其中包含 num_key 条记录。我需要比较和计算 2 月记录与 1 月记录的变化。

示例数据和预期结果:

ptn_dt = '2019-01-31'(一月)

num_key active_indicator
111 true
112 false
113 false
114 false
115 true
116 true

ptn_dt = '2019-02-28'(二月)

num_key active_indicator
111 true
112 false
113 true
114 true
115 true
116 true
117 true
118 false
119 true

预期输出:

  • 新条目计数(num_key 在 2 月,但在 1 月没有)active_indicator = 'true' ---> 2(属于 num_key 117 和 119 )
  • 1 月和 2 月期间 active_indicator 中有变化的条目数(从假到真)---> 2(属于 num_key 113 和 114
  • 1 月和 2 月之间 active_indicator 中没有变化的条目数(从真到真)---> 3(属于 num_key 111、115 和 116
  • 我可以使用什么 SQL 查询?我需要获取 2 月分区中所有 active_indicator=true 的计数,但分为 3 个输出(新条目,从 1 月到 2 月从 false 到 true,从 1 月到 2 月从 true 到 true)。

    使用全连接(全连接 returns 连接记录,加上不从左连接 table,加上不从右连接 table)。使用带 count() 的案例表达式:

    select
           count(case when t1.num_key is null then 1 else null end) as cnt_new,
           count(case when t1.active_indicator = false and t2.active_indicator = true then 1 else null end) as cnt_false_to_true,
           count(case when t1.active_indicator = true and  t2.active_indicator = true then 1 else null end) as cnt_true_not_changed
     from (select * from table t1 where t1.ptn_dt = '2019-01-31') t1
          full join (select * from table t2 where ptn_dt = '2019-02-28' ) t2
               on t1.num_key = t2.num_key