[英]How to get only rows that are the max of a column with a subquery, using one query?
Very similarly to this question , I'd like to only have rows that are the max of a column. 与此问题非常相似,我只想拥有最多一列的行。 All of these solutions seem to work great when working with a table, but I'm trying to do this with a subquery. 当使用表时,所有这些解决方案似乎都很好用,但是我试图通过子查询来实现。 I'd like to get this down to one query. 我想简化为一个查询。
The two methods I've thought of to accomplish this are: a) using temporary tables, or b) duplicate the subquery code. 我想到的两种方法是:a)使用临时表,或b)复制子查询代码。 The temporary tables method is straightforward, but forces me to use multiple queries. 临时表方法很简单,但是却迫使我使用多个查询。 The duplicate code works as well, but, well... it's duplicate code. 重复的代码也可以正常工作,但是,好吧...它是重复的代码。
What I want to do is something along the lines of an INTO within a subquery, so I can re-use the info from that subquery: 我想要做的是在子查询中执行INTO的工作,因此我可以重用该子查询中的信息:
select ...
from (
select ..., count(someColumn) as countColumn
into #tempTable
where ...
group by ...
)
where countColumn = (select max(countColumn) from #tempTable)
but apparently that's not allowed... 但显然这是不允许的...
Is this possible to do in one query, without duplicating my subquery? 是否可以在一个查询中完成而不重复子查询?
How about using a CTE? 如何使用CTE?
with t as (
select . . ., count(someColumn) as countColumn
where . . .
group by . . . .
)
select *
from t
where countColumn = (select max(CountColumn from t);
You can also do this with analytic functions: 您也可以使用分析功能执行此操作:
select *
from (select . . ., count(someColumn) as countColumn,
max(count(someColumn)) over () as maxcountColumn
where . . .
group by . . .
) t
where countColumn = maxcountColumn;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.