我试图创建一个查询,它会为所有返回的记录提供一个row_number。我可以为数据库中的所有记录执行此操作。问题是,我需要以某种方式检索内部(WHERE posts.status = 'published'
)的WHERE语句的查询的行号。
我的原始查询如下:
SELECT
posts.*,
row_number() over (ORDER BY posts.score DESC) as position
FROM posts
但是,在over()
中添加where语句会引发语法错误:
SELECT
posts.*,
row_number() over (
WHERE posts.status = 'published'
ORDER BY posts.score DESC
) as position
FROM posts
答案 0 :(得分:0)
SELECT posts.*, row_number() over (ORDER BY posts.score DESC) as position
FROM posts
WHERE posts.status = 'published'
答案 1 :(得分:0)
不太确定你的目标是什么。也许展示一个预期输出的例子。以下是一种方法示例:
create table posts(id int, score int, status text);
insert into posts values(1, 1, 'x');
insert into posts values(2, 2, 'published');
insert into posts values(3, 3, 'x');
insert into posts values(4, 4, 'x');
SELECT x.id, x.score, x.status
,CASE WHEN x.status = 'published' THEN null ELSE x.position END
FROM (SELECT posts.*,
row_number() OVER (ORDER BY posts.score DESC)
-SUM(CASE WHEN status = 'published' THEN 1 ELSE 0 END)
OVER (ORDER BY posts.score DESC) as position
FROM posts
) x
结果:
4 4 x 1
3 3 x 2
2 2 published
1 1 x 3