sql,如何防止where条件后的行号重置

mspsb9vt  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(295)

我有个问题:

SELECT ROW_NUMBER() OVER (ORDER BY total_votes desc, views desc, date desc, time desc) AS rn,
name, date, time, subject, full_address, views, total_votes, user_email, typology_name
FROM photo
ORDER BY total_votes desc, views desc, date desc, time desc;

产生这样的结果:

.
现在,我想过滤结果表,例如,我只看到第2/3/4行:

SELECT ROW_NUMBER() OVER(ORDER BY total_votes desc, views desc, date desc, time desc) AS row_num,
name, date, time, subject, full_address, views, total_votes, user_email, typology_name
FROM(
SELECT *, ROW_NUMBER() OVER (ORDER BY total_votes desc, views desc, date desc, time desc) AS rn
FROM photo) q
WHERE rn >= 2 AND rn <= 4 
ORDER BY total_votes desc, views desc, date desc, time desc;

问题是,这个查询返回这3行,但将1/2/3作为row\ num而不是2/3/4。

如何才能看到在第一个查询中看到的行号?提前谢谢。

f3temu5u

f3temu5u1#

您正在外部查询上执行第二次行号计算,而不是内部查询。所以它返回过滤查询中的行数。您应该使用以下代码:

SELECT rn, name, date, time, subject, full_address, views, total_votes, user_email, typology_name
FROM(
SELECT *, 
ROW_NUMBER() OVER (ORDER BY total_votes desc, views desc, date desc, time desc) AS rn
FROM photo) q
WHERE rn >= 2 AND rn <= 4 
ORDER BY total_votes desc, views desc, date desc, time desc;

相关问题