问题
We INSERT new records every day to a table with say id and created_on column.
How do i identify if records with a particular identifier existed every day in the last 7 days ?
回答1:
This can be done with a Stored Procedure:
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);
For the time travel query replace to work, put in an "at"
as a table alias.
The return value is an array of day offsets when the query returns any value.
This will only work beyond DAYS=2
if you have Snowflake Enterprise Edition.
回答2:
I did it with the below query
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;
来源:https://stackoverflow.com/questions/59063404/snowflake-query-if-an-id-exists-on-each-of-the-last-7-days