Search code examples
sqlt-sqlsql-server-2017

Avoiding use of a temp table by using sub queries


I want to create a subquery to avoid the use of a temp table. Right now I have:

select id,COUNT (id)as Attempts
into #tmp
from Table1
where State in ('SD')
and Date >=  cast( GETDATE() -7 as date )
group by Accountid having COUNT (accountid) > 2

select *
from #tmp a join Table1 b on a.id= b.id
and b.Date >=  cast( GETDATE() -7 as date )
where CAST(Date as date) = cast(GETDATE()-1 as date)
order by a.id,b.Date 

Is there a way to get this result in just one query?


Solution

  • Replace #tmp in the second query with the first query enclosed in parenthesis, as in:

    select *
    from (
      select id,COUNT (id) as Attempts
      from Table1
      where State in ('SD')
      and Date >=  cast( GETDATE() -7 as date )
      group by Accountid having COUNT (accountid) > 2
    ) a join Table1 b on a.id= b.id
    and b.Date >=  cast( GETDATE() -7 as date )
    where CAST(Date as date) = cast(GETDATE()-1 as date)
    order by a.id,b.Date 
    

    The first query becomes a "table expression".