2

我正在使用以下查询来获取 profile_run_key 的前两条记录。我正在使用三个几乎相似的查询来完成这项工作。这意味着我要为“where”子句遍历表三次。所以我认为这将需要 3(n) 时间来执行。或者,我可以使用“Order by”,但执行需要 nlogn 时间。

SELECT name, weighted_average
      FROM idp_weighted_avg 
           where (profile_run_key =
                   (SELECT MAX (profile_run_key)
                      FROM idp_weighted_avg
                     WHERE SCORECARD_IDENTIFIER = 'U:D8yIYvW6EeGKyklcM7Co1A')
                OR profile_run_key =
                      (SELECT MAX (profile_run_key)
                         FROM idp_weighted_avg
                        WHERE SCORECARD_IDENTIFIER = 'U:D8yIYvW6EeGKyklcM7Co1A'
                              AND profile_run_key <
                                     (SELECT MAX (profile_run_key)
                                        FROM idp_weighted_avg
                                       WHERE SCORECARD_IDENTIFIER =
                                                'U:D8yIYvW6EeGKyklcM7Co1A')))

我想知道是否可以重用(我不想创建临时表)以下子查询的结果?有什么选择吗?建议?

SELECT MAX (profile_run_key)
              FROM idp_weighted_avg
             WHERE SCORECARD_IDENTIFIER = 'U:D8yIYvW6EeGKyklcM7Co1A'
4

1 回答 1

0

似乎您正在为给定的SCORECARD_IDENTIFIER. 如果那是你真正想要的,你可以添加

  • 一种ROW_NUMBER
  • PARTITION BY SCORECARD_IDENTIFIER- 重新启动每个组的行号
  • ORDER BY profile_run_key DESC- 将组中的键编号从高到低

SQL 语句

SELECT  *
FROM    idp_weighted_avg wa
        INNER JOIN (
          SELECT  profile_run_key
                  , rn = ROW_NUMBER() OVER (PARTITION BY SCORECARD_IDENTIFIER ORDER BY profile_run_key DESC)
          FROM    idp_weighted_avg
          WHERE   SCORECARD_IDENTIFIER = 'U:D8yIYvW6EeGKyklcM7Co1A'
        ) rn ON rn.profile_run_key = wa.profile_run_key
WHERE   rn <= 2        
于 2012-09-06T13:39:32.000 回答