您好我有两个这样的查询
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 :(得分: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
子句中。
答案 1 :(得分: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
但子查询可能会导致非最佳查询计划。