SnowFlake查询最近7天内是否存在ID

时间:2019-11-27 05:13:25

标签: sql snowflake-data-warehouse snowflake-schema

我们每天将新记录插入到具有ID和created_on列的表中。

如何确定过去7天内每天是否存在具有特定标识符的记录?

2 个答案:

答案 0 :(得分:0)

这可以通过存储过程来完成:

CREATE OR REPLACE PROCEDURE TIME_TRAVEL(QUERY TEXT, DAYS FLOAT)
RETURNS VARIANT LANGUAGE JAVASCRIPT AS
$$
  function run_query(query, offset) {
    try {
      var sqlText = query.replace('"at"', " AT(OFFSET => " + (offset + 0) + ") ");
      return (snowflake.execute({sqlText: sqlText})).next();
    }
    catch(e) { return false }
  }
  var days, result = [];
  for (days = 0; days < DAYS; days++)
    if (run_query(QUERY, -days * 86400)) result.push(days);
  return result;
$$;

CALL TIME_TRAVEL('SELECT * FROM TASK_HISTORY "at" WHERE QUERY_ID = ''019024ef-002e-8f71-0000-05e10030a782''', 7);

为使时间旅行查询替换正常工作,请将"at"作为表别名。
当查询返回任何值时,返回值是一组日期偏移量。
如果您使用的是Snowflake Enterprise Edition,则仅在DAYS=2之后才能使用。

答案 1 :(得分:0)

我通过以下查询做到了

select id,  sum(present) as total_count 
from
    (select id,feed_date, count(1) as present 
    from catalog_rca 
    where feed_date between '2019-11-19' and '2019-11-25'  
    group by 1,2) as temp
group by 1 having total_count = 7;