Quantcast
Viewing all articles
Browse latest Browse all 207

How to reuse view logic with different date parameters?

Is there a way to reuse SQL logic behind a view by swapping justone DATE parameter?

Below is a sample query with CTEs showing three levels of recordsin the example.erp schema:subscriptions --< subscription_items --< count_data.

CREATE OR REPLACE VIEW example.erp.closing_mo_subscription_itemsWITH    context AS (        SELECT            DATE_FROM_PARTS(2023, 8, 31) AS ref_mo_end_date,  -- parameterize?            LAST_DAY(DATEADD(MONTH, -1, ref_mo_end_date)) AS prev_mo_end_date    ),    count_data_subscription_items AS (        SELECT            cd.subscription_item_id,            sum(cd.quantity) as total_quantity        FROM example.erp.count_data AS cd           , context AS x        WHERE            cd.start_date <= x.ref_mo_end_date AND            cd.end_date >= x.ref_mo_end_date        GROUP BY cd.subscription_item_id    ),    subscriptions_extended AS (        SELECT            s.*        FROM example.erp.subscriptions AS s           , context AS x        WHERE            s.start_date <= x.ref_mo_end_date AND            s.end_date >= x.ref_mo_end_date    ),    subscription_items_extended AS (        SELECT            s.name AS subscription_name,            cdsi.total_quantity AS usage_count,            si.*        FROM example.erp.subscription_items AS si        INNER JOIN subscriptions_extended AS s ON                   s.id = si.subscription_id        LEFT JOIN count_data_subscription_items AS cdsi ON                  cdsi.subscription_item_id = si.id           , context AS x        WHERE            si.start_date <= x.ref_mo_end_date AND            si.end_date >= x.ref_mo_end_date    )SELECT *FROM subscription_items_extended

In the CTE, context.ref_mo_end_date is applied used as a filter onrecords across all three source tables. I'd like to reuse the exact same logicin a different view that would use prev_mo_end_dateinstead of ref_mo_end_date.

Is this kind of parameterization in a view possible?

For what it's worth, I did find an older thread on a similar topicand I'm hoping there's an option in 2023 that might reduce duplicative SQL logicbehind views, while keeping the views accessible for casual data analysis.


Viewing all articles
Browse latest Browse all 207

Trending Articles