微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决通过使用子查询避免使用临时表

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

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 

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。