I am fairly new to SQL and having issues figuring out how to solve the simple issue below. I have a dataset I am trying to self-join, I am using (b.calendar_year_number -1)
as one of the columns to join. I applied a calculation of -1 with the goal of trying to match values from the previous year. However, it is not working as the resulting column shows (No column name)
with a screenshot attached below. How do I change the alias to b.calendar_year_number
after the calculation?
Code:
SELECT a.day_within_fiscal_period, a.calendar_month_name, a.cost_period_rolling_three_month_start_date, a.calendar_year_number, b.day_within_fiscal_period, b.calendar_month_name, b.cost_period_rolling_three_month_start_date, (b.calendar_year_number -1) FROM [data_mart].[v_dim_date_consumer_complaints] AS a JOIN [data_mart].[v_dim_date_consumer_complaints] AS b ON b.day_within_fiscal_period = a.day_within_fiscal_period AND b.calendar_month_name = a.calendar_month_name AND b.calendar_year_number = a.calendar_year_number
Advertisement
Answer
I am using (b.calendar_year_number -1) as one of the columns to join.
Nope, you’re not. Look at your join statement and you’ll see the third condition is:
b.calendar_year_number = a.calendar_year_number
So just change that to include the calculation. As far as the ‘no column name’ issue, you can use colname = somelogic
syntax or somelogic as colname
. Below, I used the former syntax.
select a.day_within_fiscal_period, a.calendar_month_name, a.cost_period_rolling_three_month_start_date, a.calendar_year_number, b.day_within_fiscal_period, b.calendar_month_name, b.cost_period_rolling_three_month_start_date, bCalYearNum = b.calendar_year_number from [data_mart].[v_dim_date_consumer_complaints] a left join [data_mart].[v_dim_date_consumer_complaints] b on b.day_within_fiscal_period = a.day_within_fiscal_period and b.calendar_month_name = a.calendar_month_name and b.calendar_year_number - 1 = a.calendar_year_number;