如何解决通过使用子查询避免使用临时表
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 举报,一经查实,本站将立刻删除。