Skip to content

Fix pivot.sql #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions util/pivot.sql
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
CREATE OR REPLACE FUNCTION
CREATE OR REPLACE FUNCTION
`fhoffa.x.normalize_col_name`(col_name STRING) AS (
REGEXP_REPLACE(col_name,r'[/+#|]', '_'
)
REGEXP_REPLACE(col_name,r'[/+#|]', '_')
);

CREATE OR REPLACE PROCEDURE `fhoffa.x.pivot`(
table_name STRING
, destination_table STRING
Expand All @@ -15,15 +15,15 @@ CREATE OR REPLACE PROCEDURE `fhoffa.x.pivot`(
)
BEGIN
DECLARE pivotter STRING;

EXECUTE IMMEDIATE (
"SELECT STRING_AGG(' "||aggregation
||"""(IF('||@pivot_col_name||'="'||x.value||'", '||@pivot_col_value||', null)) e_'||fhoffa.x.normalize_col_name(x.value))
||"""(IF('||@pivot_col_name||'="'||x.value||'", '||@pivot_col_value||', null)) e_'||`fhoffa.x.normalize_col_name`(x.value))
FROM UNNEST((
SELECT APPROX_TOP_COUNT("""||pivot_col_name||", @max_columns) FROM `"||table_name||"`)) x"
) INTO pivotter
) INTO pivotter
USING pivot_col_name AS pivot_col_name, pivot_col_value AS pivot_col_value, max_columns AS max_columns;

EXECUTE IMMEDIATE (
'CREATE OR REPLACE TABLE `'||destination_table
||'` AS SELECT '
Expand Down