简体   繁体   English

如何使用一个查询只获取具有子查询的列的最大值的行?

[英]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.

相关问题 如何编写sql查询以选择一列中具有最大值的行 - how to write sql query to select rows with max value in one column 如何在Postgres数据库中仅获取具有max version_id的行而无需昂贵的子查询? - How to get only rows with max version_id without expensive subquery in postgres database? 如果查询有行,如何只运行子查询? - How to only run subquery if query has rows? 如何在没有子查询的情况下汇总一列中的行? - How to agregate rows in one column without subquery? 如何使用子查询获取Oracle中的最大日期 - How to get the max date in Oracle using a subquery 如何使用分组获取(选择)具有特定列最大值的行 - How to get(select) the rows with max value of a particular column using grouping 使用group by时如何获取具有max(of of column)的行 - How to get rows with max(of a column) when using group by 如何仅查询将超过最大数量的行 - How to query only rows that will exceed to the max quantity 使用MAX计算子查询列中的MAX值 - Using MAX to compute MAX value in a subquery column 使用 DB2,如何为一列选择具有 MAX 的行,然后在结果子集上为同一表的另一列选择具有 MAX 的行? - Using DB2, how do you select rows with MAX for one column and then select rows with MAX on the resulting subset for another column on the same table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM