0

你好我有两个这样的查询

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)

你能帮我理解我应该在哪里改变吗?非常感谢你!

4

2 回答 2

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
     ) t
group by Num_Occ
ORDER BY Num_Occ;

您想将子查询放在from子句而不是where子句中。

于 2013-08-30T18:58:50.790 回答
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

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

于 2013-08-30T19:03:12.870 回答