gate the row_number function so that only target rows are processes Actuals for sales and Quotes for quotes

This commit is contained in:
Paul Trowbridge 2025-08-25 17:31:37 -04:00
parent 8974095341
commit f19bd138e3

View File

@ -1,6 +1,6 @@
REFRESH MATERIALIZED VIEW pricequote.lastpricedetail;
-- REFRESH MATERIALIZED VIEW pricequote.lastpricedetail;
--DROP MATERIALIZED VIEW pricequote.lastpricedetail
DROP MATERIALIZED VIEW pricequote.lastpricedetail;
CREATE MATERIALIZED VIEW pricequote.lastpricedetail AS
WITH base AS (
@ -28,38 +28,38 @@ WITH base AS (
ranked AS (
SELECT b.*,
-- Most recent sale (Actuals first, newest date first)
ROW_NUMBER() OVER (
CASE WHEN version = 'Actual' THEN ROW_NUMBER() OVER (
PARTITION BY customer, partgroup
ORDER BY (version = 'Actual') DESC,
odate DESC NULLS LAST
) AS rn_mrs,
) END AS rn_mrs,
-- Most recent quote (Quotes first, newest date first)
ROW_NUMBER() OVER (
CASE WHEN version = 'Quotes' THEN ROW_NUMBER() OVER (
PARTITION BY customer, partgroup
ORDER BY (version = 'Quotes') DESC,
odate DESC NULLS LAST
) AS rn_mrq,
) END AS rn_mrq,
-- Largest volume sale in last year (those inside window first)
ROW_NUMBER() OVER (
CASE WHEN version = 'Actual' THEN ROW_NUMBER() OVER (
PARTITION BY customer, partgroup
ORDER BY (version = 'Actual' AND odate >= CURRENT_DATE - INTERVAL '1 year') DESC,
qty DESC NULLS LAST
) AS rn_lvs,
) END AS rn_lvs,
-- Largest volume quote in last year (those inside window first)
ROW_NUMBER() OVER (
CASE WHEN version = 'Quotes' THEN ROW_NUMBER() OVER (
PARTITION BY customer, partgroup
ORDER BY (version = 'Quotes' AND odate >= CURRENT_DATE - INTERVAL '1 year') DESC,
qty DESC NULLS LAST
) AS rn_lvq,
) END AS rn_lvq,
-- Per dataseg/version: most recent (version fixed in partition, so just date)
ROW_NUMBER() OVER (
CASE WHEN version = 'Actual' THEN ROW_NUMBER() OVER (
PARTITION BY customer, partgroup, dataseg, version
ORDER BY odate DESC NULLS LAST
) AS rn_dss,
ROW_NUMBER() OVER (
) END AS rn_dss,
CASE WHEN version = 'Quotes' THEN ROW_NUMBER() OVER (
PARTITION BY customer, partgroup, dataseg, version
ORDER BY odate DESC NULLS LAST
) AS rn_dsq
) END AS rn_dsq
FROM base b
),
flagged AS (
@ -139,4 +139,4 @@ WITH DATA;
--SELECT * FROM pricequote.lastpricedetail;
CREATE INDEX lastpricedetail_idx ON pricequote.lastpricedetail(customer, partgroup);
CREATE INDEX lastpricedetail_idx ON pricequote.lastpricedetail(customer, partgroup);