更高效的方式来编写TOP 1 *查询?

时间:2014-10-13 21:50:00

标签: sql sql-server sql-server-2012

下面是一个查询示例,我认为这会妨碍我的存储过程的整体性能(此操作在循环中多次完成)。临时表#PROBLEMS_RELATED_REF_FINAL是几个完整外连接的结果,并且没有主键(因为您可以通过我的where子句看到,一些可能的主键列为null)。我想知道是否有更有效的方法来获得满足所有条件的最高记录(假设没有主键)。 #PROBLEMS_RELATED_REF_FINAL通常会有大约50-1000条记录。

SELECT TOP 1 *, NULL AS [SUBTRACTION], NULL AS [END_COUNTER]  
FROM #PROBLEMS_RELATED_REF_FINAL 
WHERE [ST_1] IS NOT NULL 
AND [ST_2] IS NOT NULL 
AND [ST_3] IS NOT NULL 
AND [ST_4] IS NOT NULL 

为#PROBLEMS_RELATED_REF_FINAL创建的表格如下所示:

CREATE TABLE #PROBLEMS_RELATED_REF_FINAL (
[ST_1] CHAR(2) NULL,
[PUMA_1] CHAR(5) NULL,
[ZCTA_1] CHAR(5) NULL,
[X-XX_1] INT NULL,
[PUMA_PROBLEMS_1] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_1] INT NULL,
[COUNTER_1] INT NULL,
[ST_2] CHAR(2) NULL,
[PUMA_2] CHAR(5) NULL,
[ZCTA_2] CHAR(5) NULL,
[X-XX_2] INT NULL,
[PUMA_PROBLEMS_2] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_2] INT NULL,
[COUNTER_2] INT NULL,
[ST_3] CHAR(2) NULL,
[PUMA_3] CHAR(5) NULL,
[ZCTA_3] CHAR(5) NULL,
[X-XX_3] INT NULL,
[PUMA_PROBLEMS_3] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_3] INT NULL,
[COUNTER_3] INT NULL,
[ST_4] CHAR(2) NULL,
[PUMA_4] CHAR(5) NULL,
[ZCTA_4] CHAR(5) NULL,
[X-XX_4] INT NULL,
[PUMA_PROBLEMS_4] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_4] INT NULL,
[COUNTER_4] INT NULL,
[ST_5] CHAR(2) NULL,
[PUMA_5] CHAR(5) NULL,
[ZCTA_5] CHAR(5) NULL,
[X-XX_5] INT NULL,
[PUMA_PROBLEMS_5] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_5] INT NULL,
[COUNTER_5] INT NULL,
[ST_6] CHAR(2) NULL,
[PUMA_6] CHAR(5) NULL,
[ZCTA_6] CHAR(5) NULL,
[X-XX_6] INT NULL,
[PUMA_PROBLEMS_6] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_6] INT NULL,
[COUNTER_6] INT NULL,
[ST_7] CHAR(2) NULL,
[PUMA_7] CHAR(5) NULL,
[ZCTA_7] CHAR(5) NULL,
[X-XX_7] INT NULL,
[PUMA_PROBLEMS_7] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_7] INT NULL,
[COUNTER_7] INT NULL,
[ST_8] CHAR(2) NULL,
[PUMA_8] CHAR(5) NULL,
[ZCTA_8] CHAR(5) NULL,
[X-XX_8] INT NULL,
[PUMA_PROBLEMS_8] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_8] INT NULL,
[COUNTER_8] INT NULL,
[ST_9] CHAR(2) NULL,
[PUMA_9] CHAR(5) NULL,
[ZCTA_9] CHAR(5) NULL,
[X-XX_9] INT NULL,
[PUMA_PROBLEMS_9] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_9] INT NULL,
[COUNTER_9] INT NULL,
[ST_10] CHAR(2) NULL,
[PUMA_10] CHAR(5) NULL,
[ZCTA_10] CHAR(5) NULL,
[X-XX_10] INT NULL,
[PUMA_PROBLEMS_10] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_10] INT NULL,
[COUNTER_10] INT NULL)
ON [PRIMARY]

非常感谢任何见解。

0 个答案:

没有答案