I want to optimize my code without using temporary table, is it possible? I try to use JOINS, but I dont know how to use JOIN in the same table with my conditions:
select 'Quest1' q1,
date1 as date_q1,
date1 as date_q2
into #Temp
from table1
where id in (select min(id)
from table1
where date1 = '2019-01-01'
group by sy_id, date1)
and sy_id is not null;
update #Temp
set date_q2 = table1.date1
from table1
where table1.cal_id = 7
and #Temporal.sy_id = table1.sy_id
select q1, DATEDIFF(d, date_q1, date_q2) as av
from #Temp
union all
select 'Quest2' q1, DATEDIFF(d, date_ref, date1) as av
from table1
where id in (select min(id)
from table1
where date1 = '2019-01-01'
group by sy_id, date1)
Edit, solved.
Select q1, avg(Diferencia) as av from
(select 'Quest1' q1, datediff(d, date1, (select top 1 d.date1
from table1 d
where d.cal_id = 7
and d.sy_id = sy_id)) av
from table1
where id in (select min(id)
from table1
where date1 >= '2019-01-01' group by sy_id, date1)
and sy_id is not null
union all
select 'Quest2' q1, datediff(d, date_ref, date1) av
from table1
where id in (select min(id)
from table1
where date1 >= '2019-01-01' group by sy_id)
group by q1