简体   繁体   English

选择列最大值和该行对应数据的最有效方法

[英]Most efficient way to select the max value of a column and the corresponding data for that row

As a starting point I have the following query. 首先,我有以下查询。 I know that it works and produces the result I'm looking for but could it be done in a faster/more efficient way since it will potentially be processing large amounts of data to find what I want to return. 我知道它可以工作并产生我想要的结果,但是可以以更快/更有效的方式完成,因为它可能会处理大量数据以查找我想要返回的内容。

(ID in the example below is an auto-increment PK field) (以下示例中的ID是一个自动递增的PK字段)

select x, y, z
from table
where id = (select max(id) from table where z = someValue)

I would suggest: 我会建议:

select top (1) x, y, x
from table
where z = somevalue
order by id desc;

For performance, you want an index on (z, id) . 为了提高性能,您需要在(z, id)上建立索引。

I like using a CTE for this, as you can do an INNER JOIN with the source table and the CTE. 我喜欢为此使用CTE,因为您可以对源表和CTE进行INNER JOIN

;WITH LookupCTE AS 
(
    select id = MAX(id) 
    FROM table 
    WHERE z = someValue
)
SELECT x, y, x
from table t1
INNER join LookupCTE t2 ON t1.id = t2.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 选择对应于MAX列值的列值 - Select column value corresponding to MAX column value 如何在 Oracle SQL 中查询给出一列最大值和该行对应列的数据? - How to query data in Oracle SQL that gives the max value of a column and the corresponding columns for that row? 来自存储过程的TSQL最大值是最有效的方法 - TSQL max value from stored procedure results most efficient way 排名 - 选择相应的列值为MAX(列)值 - Ranking - Select corresponding column values to a MAX(column) value 使用UNPIVOT和SELECT MAX()将行数据中的SELECT MAX()值转换为列数据 - SELECT MAX() value from row data converted into column data using UNPIVOT and SELECT MAX() 从列中选择MAX值,并从另一列中选择相应的值 - Select MAX value from column and corresponding value from another Select 最大值和按日期分组的相应行 id - Select max value AND the corresponding row id grouped by date 在clickhouse中与max()聚合时如何选择一行中的相应值? - How to select corresponding value in a row when aggregating with max() in clickhouse? SQL:选择最常出现的值,该值对应于其他列 - SQL: Select value that occurs most frequently corresponding to a different column 为html表中的每一行选择用户的最有效方法 - Most efficient way to select users for each row in an html table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM