Looking at this SQL code, I've identified several issues:
1. Missing JOIN keyword
The most critical syntax error is in the final SELECT statement:
sql
from lns
full_join ko using (cst_id, report_date)
This should be:
sql
from lns
full join ko using (cst_id, report_date)
The underscore in full_join will cause a syntax error.
2. Inconsistent column naming
In the lns CTE, you're summing balance_amt
In the ko CTE, you're summing prom_balance_amt (note the "prom_" prefix)
This inconsistency might be intentional, but it's worth verifying that these are the correct column names in their respective tables.
3. Date format inconsistency
The WHERE clauses use numeric date literals (20210101) without proper formatting. While some databases handle this, it's better practice to use proper date literals:
sql
where dm.final_flag = 1 and dm.lns_flag = 1 and REPORT_DATE >= '2021-01-01'
4. Missing lns_flag filter in ko CTE
The lns CTE filters on dm.lns_flag = 1, but the ko CTE doesn't have an equivalent filter. This might be intentional, but it's an asymmetry worth noting.
5. DISTRIBUTE ON RANDOM syntax
The distribute on random clause at the end appears to be database-specific syntax (possibly Netezza or similar). Make sure this is the correct syntax for your database system. Some systems might use different syntax like DISTRIBUTED RANDOMLY or not support this at all.
6. Table name doesn't match content
The table is named monthly_end_of_month_promo_balances, but there's no logic to ensure the data is actually end-of-month data. The query appears to include all dates >= 2021-01-01. Consider either:
Renaming the table to reflect what it actually contains
Adding logic to filter for only end-of-month dates
7. Potential performance issue
Using a FULL JOIN when you might only need a LEFT JOIN (if all customers with savings accounts also have term deposits) could impact performance. Verify if FULL JOIN is truly necessary.
Here's a corrected version addressing the main issues:
sql
create table monthly_end_of_month_promo_balances as
with lns as (
select cst_id, report_date, sum(balance_amt) as sum_lns_balance_amt
from gnb_dm.GNB.TERMDEPOSITS as dm
where dm.final_flag = 1 and dm.lns_flag = 1 and REPORT_DATE >= '2021-01-01'
group by 1, 2
),
ko as (
select cst_id, report_date, sum(prom_balance_amt) as sum_ko_balance_amt
from gnb_dm.GNB.SAVINGACCOUNTS as dm
where dm.final_flag = 1 and REPORT_DATE >= '2021-01-01'
group by 1, 2
)
select cst_id,
report_date,
coalesce(sum_lns_balance_amt, 0) as sum_lns_balance_amt,
coalesce(sum_ko_balance_amt, 0) as sum_ko_balance_amt
from lns
full join ko using (cst_id, report_date)
distribute on random