代码之家  ›  专栏  ›  技术社区  ›  Ram

基于日期列的不匹配记录计数

  •  0
  • Ram  · 技术社区  · 2 年前

    我有两张桌子。数据正在从源表移动到目标表。

    create table source_table(sno number,pick_date date);
    
    create table target_table(sno number,pick_Date date)
    
    select * from source_table
    
    sno  pick_date
    1   12-JAN-23
    3   13-JAN-23
    5   14-JAN-23
    6   14-JAN-23
    7   14-Jan-23
    2   13-JAN-23
    
    
        select * from target_table
    
        Sno  Pick_date
        1   12-JAN-23
        2   13-JAN-23
        5   14-JAN-23
    

    我想根据两个表之间的pick_date列查找丢失的记录计数。

    Result
    
    Pick_date  Count
    13-jan-23  1 
    14-jan-23  2
    

    pick_ date 2023年1月13日的目标表中仅遗漏一个记录。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Littlefoot    2 年前

    这里有一个选项。

    源数据:

    SQL> with
      2  source_table (sno, pick_date) as
      3    (select 1, date '2023-01-12' from dual union all
      4     select 3, date '2023-01-13' from dual union all
      5     select 5, date '2023-01-14' from dual union all
      6     select 6, date '2023-01-14' from dual union all
      7     select 7, date '2023-01-14' from dual union all
      8     select 2, date '2023-01-13' from dual
      9    ),
     10  target_Table (sno, pick_date) as
     11    (select 1, date '2023-01-12' from dual union all
     12     select 2, date '2023-01-13' from dual union all
     13     select 5, date '2023-01-14' from dual
     14    )
    

    查询使用 minus set运算符查找目标表中缺少的行,并统计每个日期的行数:

     15  select pick_date, count(*)
     16  from (select sno, pick_date from source_table
     17        minus
     18        select sno, pick_date from target_Table
     19       )
     20  group by pick_date;
    
    PICK_DATE    COUNT(*)
    ---------- ----------
    13.01.2023          1
    14.01.2023          2
    
    SQL>
    

    如果这些表中没有唯一的列,并且您不想键入10个不同的列,请使用 row_number 解析函数;然后重复我已经发布的代码:

     15  st as
     16    (select pick_date, row_number() over (partition by pick_date order by sno) rn
     17     from source_table
     18    ),
     19  tt as
     20    (select pick_date, row_number() over (partition by pick_date order by sno) rn
     21     from target_table
     22    )
     23  select pick_date, count(*)
     24  from (select rn, pick_date from st
     25        minus
     26        select rn, pick_date from tt
     27       )
     28  group by pick_date;
    
    PICK_DATE    COUNT(*)
    ---------- ----------
    13.01.2023          1
    14.01.2023          2
    
    SQL>