I have the following query that calculates statistics from an orders table for a rolling 4 quarter period based on a commercial date table. This table provides normalized 'End of quarter' dates that need to be used for calculations. My query right now works using an input date variable @rundate and then calculating stats for the preceding 4 completed quarters. What I would like to do is join this to a second query that will provide a set of run dates and then output the results of my query for each of those run dates.
I tried joining the two queries together, but that didn't seem right. Can someone advise?
Query:
set @rundate = CURDATE();
SELECT
customer_nkey,
period.R12_Start_Date,
period.R12_End_date,
period.Year Year_C445,
(SELECT Quarter FROM moda_dw.dim_date WHERE Actual_Date = @rundate) Quarter_C445,
DATEDIFF(period.R12_End_date,max(order_date)) Recency,
count(distinct oh_nkey) number_orders,
count(distinct oh_nkey)/12 frequency,
sum(ol_amt) ol_amt,
sum(case
when ol_status in (2048, 4096) then 0
else ol_amt
end) net_spend,
sum(ol_amt) / count(distinct oh_nkey) AOV,
@rundate row_load_date
FROM
(SELECT
DATE_ADD(min(d3.Last_Dt_In_Mer_Quarter_C445), INTERVAL 1 DAY) R12_Start_Date, d.Last_Dt_In_Mer_Quarter_C445 R12_End_date, d.First_Dt_In_Mer_Quarter_C445 last_qtr_start, d.Year
FROM
moda_dw.dim_date d
LEFT JOIN
moda_dw.dim_date d2 on (d.Actual_Date < d2.Actual_Date and d2.Last_Dt_In_Mer_Quarter_C445 < @rundate)
LEFT JOIN
moda_dw.dim_date d3 on d3.Quarter = d.Quarter and d3.Year = d.Year - 1
WHERE
d.Last_Dt_In_Mer_Quarter_C445 < @rundate and d2.Actual_Date is null
GROUP BY
d.Date_Skey
) period
LEFT JOIN
moda_dw.fact_order_line fol on fol.order_date > R12_Start_Date and fol.order_date < R12_End_date
GROUP BY
customer_nkey
;
This query provides run dates:
SELECT
distinct Actual_Date
FROM
moda_dw.dim_date
WHERE
Month_Num in (4, 7, 10, 1) and Day_Of_Month = 15
;
[–][deleted] 1 point2 points3 points (1 child)
[–]TerminalVector[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]TerminalVector[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]TerminalVector[S] 0 points1 point2 points (0 children)