简体   繁体   English

如何优化使用多个子选择语句的查询

[英]How to optimise a query that uses multiple sub select statements

was hoping some-one could help me with this: My table is: 我希望有人可以帮助我:我的表是:

id  Version  datetime     name     resource 
---|--------|------------|--------|--------- 
1  | 1      | 03/03/2009 | con1   | 399  
2  | 2      | 03/03/2009 | con1   | 244 
3  | 3      | 01/03/2009 | con1   | 555 
4  | 1      | 03/03/2009 | con2   | 200 
5  | 2      | 03/03/2009 | con2   | 500 
6  | 3      | 04/03/2009 | con2   | 600 
7  | 4      | 31/03/2009 | con2   | 700 

I need to select each distinct "name" that has greatest value of "datetime" that less than or equal to a given date; 我需要选择具有小于或等于给定日期的“datetime”最大值的每个不同“名称”; and where the version is the maximum version if there are multiple records that satisfy the first condition. 如果有多个记录满足第一个条件,那么版本是最大版本。

The result if the given date were '04/03/2009' would be: 如果给定日期为'04 / 03/2009',结果将是:

id  Version  datetime     name     resource 
---|--------|------------|--------|--------- 
2  | 2      | 03/03/2009 | con1   | 244  
6  | 3      | 04/03/2009 | con2   | 600 

Currently I've created the following query, which works, but I suspect it's not the best when it comes to performance when run on a large table: 目前我已经创建了以下查询,它可以工作,但我怀疑它在大型表上运行时的性能并不是最好的:

SELECT [id], [Version], [datetime], [name], [resource]  
FROM theTable
WHERE [Version] = 
(
SELECT MAX(Version) FROM theTable AS theTable2 WHERE theTable.[name] = theTable2.[name] 
AND  theTable2.[datetime] = 
    (
    SELECT MAX(theTable3.[datetime]) FROM theTable AS theTable3 
    WHERE theTable2.[name] = theTable3.[name] AND theTable3.[datetime] <= '04/03/2009'
    )
)

I'd appreciate if some-one could suggest a more efficient way to do this; 如果有人能提出更有效的方法,我会很感激; and if possible, provide an example:-). 如果可能的话,提供一个例子:-)。

Thanks in advance. 提前致谢。

You can use PARTITION BY. 您可以使用PARTITION BY。 This lets you basically rank the results. 这使您基本上可以对结果进行排名。 In your instance, you then want to select only the result with ranking 1. First, filter out the results with invalid date times (using WHERE), then in the partition, order by the columns descending (thus, the first result would be the one with the maximum datetime, and, in case of datetime tie, the maximum version as well.) 在您的实例中,您希望仅选择排名为1的结果。首先,使用无效日期时间过滤掉结果(使用WHERE),然后在分区中按列降序排序(因此,第一个结果将是一个具有最大日期时间,并且,在datetime tie的情况下,也是最大版本。)

SELECT [id], [Version], [datetime], [name], [resource]
FROM
(
   SELECT [id], [Version], [datetime], [name], [resource], row_number() 
     OVER (PARTITION BY [name] ORDER BY [datetime] DESC, [Version] DESC) as groupIndex
   FROM theTable
   WHERE [datetime] <= '04/03/2009'
) AS t
WHERE groupIndex = 1

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM