[英]How to concat columns in SQL?
PostgreSQL 15.0 我想进行一个查询,将两个不同的列合并为一个。
我在示例中显示的期望结果(它不是真实的,但理解这个示例会很有用)。
我使用过 CONCAT 但它不会创建新列,只是连接。 如何得到:
id Col1 Col2
1 foo 10
2 bar 42
3 baz 14
到
id NewColumn
1 foo: 10
2 bar: 42
3 baz: 14
create table t (id int, col1 text, col2 int);
insert into t values
(1, 'foo', 10),
(2, 'bar', 42),
(2, 'baz', 14),
(2, null, 14),
(2, 'wow', null);
select id, coalesce(col1, '') || ': ' || coalesce(col2::text, '') AS NewColumn FROM t
在此处查看现场演示https://www.db-fiddle.com/f/sNANpwdUPdJfUaSQ77MQUM/1
并在此处阅读文档https://www.postgresql.org/docs/current/functions-string.html
并且不要忘记 null 值
但是如果你想在表中创建一个真正的新列作为连接的结果:
alter table t
add column NewColumn text
GENERATED ALWAYS AS (
coalesce(col1, '') || ': ' || coalesce(col2::text, '')
) STORED;
select id, NewColumn FROM t
在此处查看现场演示https://www.db-fiddle.com/f/sNANpwdUPdJfUaSQ77MQUM/2
和文档https://www.postgresql.org/docs/current/ddl-generated-columns.html
您可以使用以下语句,
select id, Col1||': '||Col2 as NewColumn from table_name;
为了同时获得 Col1 和 Col2,您可以在下面使用,
select id, Col1, Col2, Col1||': '||Col2 as NewColumn from table_name;
SELECT Name, CONCAT(col1, " ", col2) AS NewColumn FROM Data;
此代码连接表中的 2 列,请在此处查看更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.