根据条件连接行
Concat rows based on condition
我正在使用具有这样值的 table
ID
Name
Value
123
Size
1
123
Size
2
123
Size
3
123
Type
Shoes
234
Size
6
234
Size
7
234
Type
Shirt
如果名称 = 大小,我想对答案进行 CONCAT。所以,我很想这样做:
ID
Name
Value
123
Size
1, 2, 3
123
Type
Shoes
234
Size
6, 7
234
Type
Shirt
我的想法是在 size = 'name' 时使用 case 然后 concat?但我不确定这是否是正确的用法。非常感谢。
您可以使用 string_agg
:
SELECT id, name, string_agg(value, ',')
FROM a
GROUP BY id, name
ORDER BY 1,2
输出:
ID
Name
value
123
Size
1,2,3
123
Type
Shoes
234
Size
6,7
234
Type
Shirt
这里 dbfiddle 展示了它是如何工作的。这是假设只有一列 name = Type,如果有更多,这也会合并它们。
我正在使用具有这样值的 table
ID | Name | Value |
---|---|---|
123 | Size | 1 |
123 | Size | 2 |
123 | Size | 3 |
123 | Type | Shoes |
234 | Size | 6 |
234 | Size | 7 |
234 | Type | Shirt |
如果名称 = 大小,我想对答案进行 CONCAT。所以,我很想这样做:
ID | Name | Value |
---|---|---|
123 | Size | 1, 2, 3 |
123 | Type | Shoes |
234 | Size | 6, 7 |
234 | Type | Shirt |
我的想法是在 size = 'name' 时使用 case 然后 concat?但我不确定这是否是正确的用法。非常感谢。
您可以使用 string_agg
:
SELECT id, name, string_agg(value, ',')
FROM a
GROUP BY id, name
ORDER BY 1,2
输出:
ID | Name | value |
---|---|---|
123 | Size | 1,2,3 |
123 | Type | Shoes |
234 | Size | 6,7 |
234 | Type | Shirt |
这里 dbfiddle 展示了它是如何工作的。这是假设只有一列 name = Type,如果有更多,这也会合并它们。