2014-10-30 24 views
0

非常类似于this question,我想只有行是列的最大值。所有这些解决方案似乎在使用表格时效果很好,但我试图用子查询来实现。我想把它归结为一个查询。如何仅使用一个查询获取具有子查询的列的最大值的行?

我认为要完成这两个方法是:a)使用临时表,或b)复制子查询代码。临时表方法很简单,但迫使我使用多个查询。重复的代码也可以工作,但是,它是重复的代码。

我想要做的是沿着一个子查询中的INTO线的东西,所以从子查询,我可以重复使用的信息:

select ... 
from (
    select ..., count(someColumn) as countColumn 
    into #tempTable 
    where ... 
    group by ... 
) 
where countColumn = (select max(countColumn) from #tempTable) 

但显然这是不允许的......

这是可能的在一个查询中做,而不重复我的子查询?

回答

1

如何使用CTE?

with t as (
     select . . ., count(someColumn) as countColumn 
     where . . . 
     group by . . . . 
    ) 
select * 
from t 
where countColumn = (select max(CountColumn from t); 

您还可以使用分析函数做到这一点:

select * 
from (select . . ., count(someColumn) as countColumn, 
      max(count(someColumn)) over() as maxcountColumn 
     where . . . 
     group by . . . 
    ) t 
where countColumn = maxcountColumn; 
相关问题