forked from dbt-labs/dbt-utils
-
Notifications
You must be signed in to change notification settings - Fork 1
/
get_column_values.sql
40 lines (28 loc) · 1.02 KB
/
get_column_values.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
{#
This macro fetches the unique values for `column` in the table `table`
Arguments:
table: A model `ref`, or a schema.table string for the table to query (Required)
column: The column to query for unique values
max_records: If provided, the maximum number of unique records to return (default: none)
Returns:
A list of distinct values for the specified columns
#}
{% macro get_column_values(table, column, max_records=none) -%}
{%- call statement('get_column_values', fetch_result=True) %}
select
{{ column }} as value
from {{ table }}
group by 1
order by count(*) desc
{% if max_records is not none %}
limit {{ max_records }}
{% endif %}
{%- endcall -%}
{%- set value_list = load_result('get_column_values') -%}
{%- if value_list and value_list['data'] -%}
{%- set values = value_list['data'] | map(attribute=0) | list %}
{{ return(values) }}
{%- else -%}
{{ return([]) }}
{%- endif -%}
{%- endmacro %}