Skip to content

Instantly share code, notes, and snippets.

@ContrastingSounds
Last active January 26, 2018 15:28
Show Gist options
  • Save ContrastingSounds/690db2267580cb8b1639303f6d08440f to your computer and use it in GitHub Desktop.
Save ContrastingSounds/690db2267580cb8b1639303f6d08440f to your computer and use it in GitHub Desktop.
Using Liquid templating to simplify a CROSS JOIN in BiqQuery (un-pivoting a table)
view: outlays {
derived_table: {
sql:
SELECT
account_name,
agency_name,
bureau_name,
subfunction_title,
treasury_agency_code,
CAST(REPLACE(outlays.TQ, ",", "") AS INT64) AS tq,
TIMESTAMP(DATE(years.year, 1, 1)) AS year,
CASE years.year
{% for i in (1962..2021) %}
WHEN {{ i }} THEN CAST(REPLACE(outlays.y{{ i }}, ",", "") AS INT64)
{% endfor %}
ELSE NULL
END AS outlay
FROM us_budget.outlays
CROSS JOIN (
SELECT year FROM (SELECT * FROM UNNEST (GENERATE_ARRAY(1962, 2021, 1)) AS year)
) years
;;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment