Multiple Case Statements Wildcard matches

derrickt
Tue, 29 Nov 2022 07:49:33 +0000
Help

Hello!

I’m trying to create a set something similar to the following

{%- set payment_methods = ['bank_transfer', 'credit_card', 'coupon', 'gift_card'] -%}

with payments as (
   select * from {{ ref('stg_payments') }}
),

final as (
   select
       order_id,
       {% for payment_method in payment_methods -%}

       sum(case when payment_method = '{{ payment_method }}' then amount else 0 end)
            as {{ payment_method }}_amount

       {%- if not loop.last -%}
         ,
       {% endif -%}

       {%- endfor %}
   from {{ ref('stg_payments') }}
   group by 1
)

select * from final

However, instead of setting the payment methods to be exact matches, I would like to use Wildcard matches.
e.g.

CASE WHEN payment_method LIKE %Amex% THEN "Credit Card"
        ELSE
           WHEN payment_method LIKE %Paynow% THEN "Bank Transfer" ELSE "Others" END

My current SQL in the dbt model has many lines of case statements and within each case statements many different variations of wildcard matches.

Appreciate some help on improving upon this and making the model cleaner with lesser lines of code and also making it easier to add on more variations of wildcard matches.

Thanks!

3 posts - 2 participants