通过使用子查询避免使用临时 table

Avoiding use of a temp table by using sub queries

我想创建一个子查询以避免使用临时文件 table。现在我有:

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 

有没有办法在一次查询中得到这个结果?

将第二个查询中的 #tmp 替换为括号中的第一个查询,如:

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 

第一个查询变为“table 表达式”。