2013-08-30 72 views
0

您好,我有两个疑问这样SQL使用子查询

select COUNT(*)as Num_Occ, trial 
into ##temp_occ 
from [E1].[dbo].[EVENT_SIM] 
where MODELING_ID=1 
group by trial,MODELING_ID 
order by TRIAL 

select Num_Occ, count(*)as Num_Trials 
from ##temp_occ 
group by Num_Occ ORDER BY Num_Occ 

我不希望创建临时表做这一切的时候合并查询,所以我使用子查询将二者结合起来。但是,我的代码返回错误,说无效名称Num_Occ。

select Num_Occ, count(*)as Num_Trials 
from [E1].[dbo].[EVENT_SIM] 
where NUM_Occ in (select COUNT(*)as Num_Occ 
from [E1].[dbo].[EVENT_SIM] 
where MODELING_ID=1) 

你能帮我理解我应该改变的地方吗?非常感谢你!

+0

如果你可以发布表格模式,并且对目标和你想要达到的目标稍作解释,那会更好。 – Rijul

回答

0

这里是将它们结合起来的方式:你想把子查询from条款不where子句中

select Num_Occ, count(*) as Num_Trials 
from (select COUNT(*) as Num_Occ, trial 
     from [E1].[dbo].[EVENT_SIM] 
     where MODELING_ID = 1 
     group by trial, MODELING_ID 
    ) t 
group by Num_Occ 
ORDER BY Num_Occ; 

0

两个查询可以组合:

select Num_Occ, count(*)as Num_Trials 
from (

select COUNT(*)as Num_Occ, trial 
from [E1].[dbo].[EVENT_SIM] 
where MODELING_ID=1 
group by trial,MODELING_ID 


) as temptable 
group by Num_Occ ORDER BY Num_Occ 

但子查询可能会导致非最佳的查询计划。