【问题标题】:SQL - Snowflake Minus OperatorSQL - 雪花减号运算符
【发布时间】:2020-12-22 11:22:12
【问题描述】:

您好,我正在运行查询以检查两个日期之间表中的任何更改......

SELECT * FROM TABLE_A where run_time = current_date() 
MINUS
SELECT * FROM TABLE_A where run_time = current_date()-1 

第一个 select 语句(其中 run_time = current_date() 返回 3,357,210 条记录。 第二条 select 语句(其中 run_time = current_date()-1 返回 0 条记录。

使用 MINUS 运算符,我预计会看到 3,357,210 条记录 (3,357,210 - 0),但结果却是 2,026,434

有什么想法吗?谢谢

【问题讨论】:

  • 选择DISTINCT会得到什么?
  • 您提出了四个问题,都有答案,但您既没有赞成也没有接受任何个问题。请保持礼貌并解决这个疏忽?
  • @MatBailie - Crikey - 耐心是我的美德。
  • @HoneyBadger 谢谢 - 这是一个明显的问题!

标签: sql union snowflake-cloud-data-platform


【解决方案1】:

https://docs.snowflake.com/en/sql-reference/operators-query.html#minus-except

从一个查询的结果集中删除出现在另一个查询的结果集中的行,使用重复消除

因此,您在第一个查询中只有 2,026,434 个唯一值。丢失的一百万位是重复的,已被消除。

【讨论】:

    【解决方案2】:

    这个查询:

    SELECT * FROM TABLE_A where run_time = current_date() 
    MINUS
    SELECT * FROM TABLE_A where run_time = current_date()-1 
    

    将始终返回来自Table_A 的所有唯一行。为什么?因为run_time 是列之一,并且在两个查询中是不同的。 MINUS 查看所有列。请注意,即使第二个查询返回行也是如此,因为行上的值不同。

    如果您的总数与总行数不同,那么您的表格中有重复项。

    这里有两种获取新记录的方法。让我假设相同的记录由col1/col2标识:

    select col1, col2
    from table_a
    where run_time in (current_date(), current_date() -1)
    group by col1, col2
    having min(run_time) = current_date();
    

    也就是说,第一次出现的是当前日期。

    或者:

    select col1, col2
    from table_a a
    where a.run_time = current_date() and
          not exists (select 1
                      from table_a a2
                      where a2.run_time = current_date() - 1 and
                            a2.col1 = a.col1 and a2.col2 = a.col2
                     );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-04-19
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      相关资源
      最近更新 更多