PostgreSQL: 枚举SQL 查询结果
PostgreSQL: Enumerate SQL query result
考虑以下 SQL 查询和响应:
CREATE TEMPORARY TABLE dreams (name text, type text);
INSERT INTO dreams VALUES ('Monkey', 'nice');
INSERT INTO dreams VALUES ('Snake', 'Not nice');
INSERT INTO dreams VALUES ('Donkey', 'nice');
INSERT INTO dreams VALUES ('Bird', 'nice');
SELECT name from dreams WHERE type='nice' ORDER BY name;
name
--------
Bird
Donkey
Monkey
(3 rows)
为了方便起见,我想按照出现的顺序枚举结果,而不考虑任何现有的 id。预期的结果应该是 a-la:
SELECT <magic_enumeration>, name from dreams WHERE type='nice' ORDER BY name;
magic_enumeration | name
-------------------+--------
1 | Bird
2 | Donkey
3 | Monkey
(3 rows)
知道如何按出现顺序枚举查询结果吗?
尝试使用 row_number,这是一个窗口函数
SELECT row_number() OVER (ORDER BY name) sid, <-- magic enumeration!
name
FROM dreams
WHERE type='nice'
ORDER BY name;
考虑以下 SQL 查询和响应:
CREATE TEMPORARY TABLE dreams (name text, type text);
INSERT INTO dreams VALUES ('Monkey', 'nice');
INSERT INTO dreams VALUES ('Snake', 'Not nice');
INSERT INTO dreams VALUES ('Donkey', 'nice');
INSERT INTO dreams VALUES ('Bird', 'nice');
SELECT name from dreams WHERE type='nice' ORDER BY name;
name
--------
Bird
Donkey
Monkey
(3 rows)
为了方便起见,我想按照出现的顺序枚举结果,而不考虑任何现有的 id。预期的结果应该是 a-la:
SELECT <magic_enumeration>, name from dreams WHERE type='nice' ORDER BY name;
magic_enumeration | name
-------------------+--------
1 | Bird
2 | Donkey
3 | Monkey
(3 rows)
知道如何按出现顺序枚举查询结果吗?
尝试使用 row_number,这是一个窗口函数
SELECT row_number() OVER (ORDER BY name) sid, <-- magic enumeration!
name
FROM dreams
WHERE type='nice'
ORDER BY name;