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

问题描述

我想创建一个查询以避免使用临时表。现在我有

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 

第一个查询变成了“表表达式”。