Useful SQL Code
Last updated: 10/21/2022
SQL
Rolling Window
Moving Average
6 week moving average
SELECT LY_WEEK_OF,
WEEK_OF,
ROUND(AVG(LY_SPEND) OVER (ORDER BY WEEK_OF ROWS BETWEEN 7 PRECEDING AND CURRENT ROW), 0) LY_SPEND,
ROUND(CASE WHEN WEEK_OF >= TRUNC(SYSDATE, 'IW') THEN NULL ELSE AVG(SPEND) OVER (ORDER BY WEEK_OF ROWS BETWEEN 7 PRECEDING AND CURRENT ROW) END, 0) SPEND
FROM SPEND_TABLE
Dangers of Lag/Lead
If a table is missing data, this can lead to all sorts of problems
Exclude Join
Below is a query to get everything from A that does not join onto B.
Full Join
I used to think this function is useless and would only use left joins. Turns out there are many situations where a full join can be useful.
For example, I had a table R that had marketing revenue and a table S that had marketing spends.
This is my original query:
Now, I can calculate ROAS because I can get REVENUE/SPENDS.
After closer look, I realized that there were some marketing spends that did not have marketing revenue (I hadn't linked them properly).
Using the full join, now I include the marketing spends that I would have missed.
Dense Rank vs. Rank vs. Row_number()
Fetch First 10 Rows Only
PL/SQL
Create Blank Table using Columns from Other Table
Create Partitions
Drop Partition Function
Insert into Append Procedure
Drop and Rebuild Procedure
Job Scheduler
Last updated