Is there a way to create a view in snowflake that would hold the Pivot data from the dynamic pivot technique? I am able to run the code and it works good but I would like to use it as a view the pivot column names changes, which is why I like the dynamic Pivot technique.
select name pivot_column
, date_trunc(quarter, month) month
, sum(month_views) pivot_value
from hero_views
group by 1,2;
call pivot_prev_results();
select *
from table(result_scan(last_query_id(-2)));
create or replace procedure pivot_prev_results()
returns string
language javascript
execute as caller as
$$
var cols_query = `
select '\\''
|| listagg(distinct pivot_column, '\\',\\'') within group (order by pivot_column)
|| '\\''
from table(result_scan(last_query_id(-1)))`;
var stmt1 = snowflake.createStatement({sqlText: cols_query});
var results1 = stmt1.execute();
results1.next();
var col_list = results1.getColumnValue(1);
pivot_query = `
select *
from (select * from table(result_scan(last_query_id(-2))))
pivot(max(pivot_value) for pivot_column in (${col_list}))
`
var stmt2 = snowflake.createStatement({sqlText: pivot_query});
stmt2.execute();
return `select * from table(result_scan('${stmt2.getQueryId()}'));\n select * from table(result_scan(last_query_id(-2)));`;
$$;