如何将数字添加到postgresql group by子句中的分组行
How to add numbers to grouped rows in postgresql group by clause
我有一个 PostgreSQL table,在文本列中包含重复值。它看起来像这样:
gid, capt
1, foo
2, foo
3, bar
4, bar
5, bar
6, buz
7, buz
我需要为组中的每个值添加一个具有不同数字的列,因此我的 table 应该如下所示:
gid, capt, rnum
1, foo, 1
2, foo, 2
3, bar, 1
4, bar, 2
5, bar, 3
6, buz, 1
7, buz, 2
它是每组内的一种行号,总是从1开始。谁能给我一个合适的SELECT声明?
这可以使用 window functions:
select gid,
capt,
row_number() over (partition by capt order by gid) as rnum
from the_table
order by capt, gid;
在 this question and its answers 的帮助下:
SELECT gid, capt, row_number() OVER (PARTITION BY capt ORDER BY gid) AS rnum
FROM your_table_here ORDER BY gid;
row_number
window function 提供计数。
OVER
子句中的 PARTITION BY
语句告诉数据库在每次更改为 capt
时重新开始编号。 OVER
子句中的 ORDER BY
告诉数据库与 gid 列一起计数。
我有一个 PostgreSQL table,在文本列中包含重复值。它看起来像这样:
gid, capt
1, foo
2, foo
3, bar
4, bar
5, bar
6, buz
7, buz
我需要为组中的每个值添加一个具有不同数字的列,因此我的 table 应该如下所示:
gid, capt, rnum
1, foo, 1
2, foo, 2
3, bar, 1
4, bar, 2
5, bar, 3
6, buz, 1
7, buz, 2
它是每组内的一种行号,总是从1开始。谁能给我一个合适的SELECT声明?
这可以使用 window functions:
select gid,
capt,
row_number() over (partition by capt order by gid) as rnum
from the_table
order by capt, gid;
在 this question and its answers 的帮助下:
SELECT gid, capt, row_number() OVER (PARTITION BY capt ORDER BY gid) AS rnum
FROM your_table_here ORDER BY gid;
row_number
window function 提供计数。
OVER
子句中的 PARTITION BY
语句告诉数据库在每次更改为 capt
时重新开始编号。 OVER
子句中的 ORDER BY
告诉数据库与 gid 列一起计数。