Skip to content

Commit

Permalink
Merge pull request dbt-labs#83 from alexcampana/unpivot-fix
Browse files Browse the repository at this point in the history
fix for excluding last column in unpivot macro
  • Loading branch information
drewbanin authored Oct 9, 2018
2 parents d0a90fe + 0083a57 commit 820aadb
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions macros/sql/unpivot.sql
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ Arguments:

{%- set exclude = exclude if exclude is not none else [] %}

{%- set include_cols = [] %}

{%- set table_columns = {} %}

{%- set _ = table_columns.update({table: []}) %}
Expand All @@ -26,18 +28,22 @@ Arguments:
{%- set cols = adapter.get_columns_in_table(schema, table_name) %}

{%- for col in cols -%}

{%- if col.column not in exclude -%}
select
{%- for exclude_col in exclude %}
{{ exclude_col }},
{%- endfor %}
cast('{{ col.column }}' as varchar) as field_name,
{{ dbt_utils.safe_cast(field=col.column, type=cast_to) }} as value
from {{ table }}
{% if not loop.last -%}
union all
{% endif -%}
{%- endif -%}
{%- if col.column not in exclude -%}
{% set _ = include_cols.append(col) %}
{%- endif %}
{%- endfor %}

{%- for col in include_cols -%}

select
{%- for exclude_col in exclude %}
{{ exclude_col }},
{%- endfor %}
cast('{{ col.column }}' as varchar) as field_name,
{{ dbt_utils.safe_cast(field=col.column, type=cast_to) }} as value
from {{ table }}
{% if not loop.last -%}
union all
{% endif -%}
{%- endfor -%}
{%- endmacro %}

0 comments on commit 820aadb

Please sign in to comment.