【问题标题】:Compare two SQL tables and return count of rows with changes比较两个 SQL 表并返回有变化的行数
【发布时间】:2021-07-26 14:21:43
【问题描述】:

我从一个包含 num_key 记录的 SQL 表中有两个分区。我需要比较和计算 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

预期输出:

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

    【问题讨论】:

    • 也许首先你应该通过num_keyJOIN 他们(但我不记得是否应该是INNER JOINOUTER JOIN 或其他),对于每个num_key,你都会在一行中有两个值(FEB,JAN)。因此,您可以比较它们以获得有变化和没有变化。如果您在JAN 中获得None,那么您将知道它是FEB 中的新值。
    • @JMDR 。 . .我已经回答了这个问题。

    标签: python sql hive hiveql


    【解决方案1】:

    使用全联接(全联接返回联接记录,加上未从左表联接,加上未从右表联接)。用 count() 使用 case 表达式:

    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   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 2014-02-26
      • 1970-01-01
      相关资源
      最近更新 更多