首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过使用子查询避免使用临时表

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

Stack Overflow用户
提问于 2021-07-09 01:19:47
回答 1查看 28关注 0票数 0

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

代码语言:javascript
复制
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 

有没有办法只用一次查询就能得到这个结果?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-09 01:48:28

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

代码语言:javascript
复制
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 

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68306134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档