我想在不使用临时表的情况下优化代码,这可能吗? 我尝试使用JOINS,但是我不知道如何在符合条件的同一个表中使用JOIN:
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)
编辑,解决。
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
答案 0 :(得分:0)
更具体地说: Select first row in each GROUP BY group?
使用此查询按组选择顶部行,然后即可加入。
或者,您可以使用子查询:
SELECT
date_diff(
some_date,
#subquery - min date or whatever
SELECT MIN (...) FROM "x" AS "x2" WHERE "x2"."id"="x1"."id"
)
FROM "x" AS "x1"