我使用下面的查询来获取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'
答案 0 :(得分:0)
您似乎正在为给定的SCORECARD_IDENTIFIER
选择两个最大的记录。如果这是你真正想要的,你可以添加
ROW_NUMBER
PARTITION BY SCORECARD_IDENTIFIER
- 重新启动每个群组的rownumber 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