I had a scenario which I need to write a query.
I had a Query1
which return hundreds of records with these four column names (batch_no, batch_name, class_no, class_name
) based on some joins. I need to write a final query (Query2
) to return columns from other tables which uses class_no
and batch_no
column values returned by Query1
.
My final query (query2
) should return these columns for the all records returned by the query1
:
Batch_global_Id (in table global_details),
batch_no, batch_name, class_no, class_name,
Start_year, End_year (from table time_details)
Global_details
has class_no
column so that we can join the results of query1 with Global_details
to get the values for the column Batch_global_Id
in the final query (Query2
).
But the problem here is to get the Start_year
and End_year
values from the table time_details
. We need get the two field values for all the records return by query1 based on class_no, batch_no
.
Here is the condition to get those values (Start_year, End_year
).
If there is a record in
time_details
table with thatclass_no
, we need to getStart_year
andEnd_year
from that record in the final output query.If there is no record in
time_details
table with thatclass_no
, then get theStart_year
andEnd_year
values from the record with matchingbatch_no
in thetime_details
table.If neither exists (NO record in
time_details
table with the matchingclass_no
&batch_no
), then get theStart_year
andEnd_year
values from the record intime_details
withbatch_no = null
Can some one help me in writing this query?
Edit as per comment
Select
batch_no, batch_name, class_no, class_name
into
#temptable
from
... (query1) ...
Expected query
Select
gd.Batch_global_Id,
tt.batch_no, tt.batch_name, tt.class_no, tt.class_name,
td.Start_year, td.End_year
from
Global_details gd
inner join
time_details td on gd.class_no = td.class_no
inner join
**something like to get values from time_details table based on the above condition//**