简体   繁体   English

在没有临时表的情况下优化我的SQL代码

[英]Optimize my SQL code without temporary table

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: 我尝试使用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)

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

You should check CTEs : https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-2017 您应该检查CTE: https ://docs.microsoft.com/zh-cn/sql/t-sql/queries/with-common-table-expression-transact-sql ? view = sql-server-2017

More specifically: Select first row in each GROUP BY group? 更具体地说: 在每个GROUP BY组中选择第一行?

Use this query to select top row by group, then you can join. 使用此查询按组选择顶部行,然后即可加入。

Alternatively you can use a subquery: 或者,您可以使用子查询:

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM