From d32ce76299fa7277a26bdc89243199657d0bb925 Mon Sep 17 00:00:00 2001 From: Alex Campana Date: Wed, 12 Sep 2018 10:44:51 -0400 Subject: [PATCH] fix for excluding last column in unpivot --- macros/sql/unpivot.sql | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/macros/sql/unpivot.sql b/macros/sql/unpivot.sql index 0ba489b8..313efd33 100644 --- a/macros/sql/unpivot.sql +++ b/macros/sql/unpivot.sql @@ -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: []}) %} @@ -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 %}