您可以使用 ROW_NUMBER()
ROW_NUMBER()
select ROW_NUMBER() OVER (PARTITION BY project_id ORDER BY sector) as id, project_id, sector from (select id as project_id, unnest(string_to_array(sector, '#')) as sector from project) as t;
你可以结合使用 string_to_array 和 unnest
string_to_array
unnest
select id, unnest(string_to_array(sector, '#')) as sector, project from project;
此查询的输出当然可以连接到其他表。为了便于阅读,我更喜欢将其放入公用表表达式中。
with normalized_projects as ( select id, unnest(string_to_array(sector, '#')) as sector, project from project ) select p.id as project_Id, row_number() over (partition by p.id order by sector) as new_sector_id, p.sector, p.project, s.sector_id from normalized_projects p join sector s on s.sector_name = p.sector;
您可能还需要考虑将该规范化结构视为一个视图,这样您就不必在整个地方重复该查询
SQLFiddle示例: http://sqlfiddle.com/#!15/1fc14/3