[英]How to combine values from same column into a new column based on similar id
So right now, I have a table, baseoil, that includes a description column, a substring column that has parsed data from the description column, and a ID column.所以现在,我有一个表 baseoil,它包括一个描述列、一个从描述列解析数据的子字符串列和一个 ID 列。 I want to combine the parsed values from the substring into a new column based on the the ID of the row while also keeping the data that does not have a duplicate ID.
我想根据行的 ID 将来自子字符串的解析值组合到一个新列中,同时保留没有重复 ID 的数据。 For example:
例如:
Description |Substring |ID |
---------------------|-----------|-------|
100 GALLONS OF SN5484|100 GALLONS|8330780|
---------------------|-----------|-------|
100 GALLONS OF SN5484|SN5484 |8330780|
---------------------|-----------|-------|
25 LITERS OF TY50000 |TY50000 |7545215|
I want the new row to look like this:我希望新行看起来像这样:
Description |Substring |ID |Combined |
---------------------|-----------|-------|------------------|
100 GALLONS OF SN5484|100 GALLONS|8330780|100 GALLONS SN5484|
---------------------|-----------|-------|------------------|
100 GALLONS OF SN5484|SN5484 |8330780|100 GALLONS SN5484|
---------------------|-----------|-------|------------------|
25 LITERS OF TY50000 |TY50000 |7545215|TY50000 |
How would I go about doing this?我该怎么做呢?
One option is to join the table with an aggregate query that computes the combined substring
s for each id
:一种选择是将表与聚合查询连接起来,该查询计算每个
id
的组合substring
s :
select b.*, c.combined
from baseoil b
inner join (select id, string_agg(substring, ' ') combined from baseoil group by id) c
on b.id = c.id
Demo on DB Fiddle : DB Fiddle 上的演示:
description | substring | id | combined :-------------------- | :---------- | ------: | :----------------- 100 GALLONS OF SN5484 | 100 GALLONS | 8330780 | 100 GALLONS SN5484 100 GALLONS OF SN5484 | SN5484 | 8330780 | 100 GALLONS SN5484 25 LITERS OF TY50000 | TY50000 | 7545215 | TY50000
Use string_agg()
as a window function:使用
string_agg()
作为窗口函数:
select bo.*,
string_agg(substring order by ?, ' ') over (partition by id) as combined
from baseoil bo;
The ?
?
is for the column that specifies the ordering.用于指定排序的列。 Otherwise, the substrings may be combined in any arbitrary ordering.
否则,子串可以按任意顺序组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.