[英]How to concat columns in SQL?
PostgreSQL 15.0 I want to make a query that concats two different columns into one. PostgreSQL 15.0 我想进行一个查询,将两个不同的列合并为一个。
Desired outcome I showed in the exapmle (it's not a real one but it would be useful to understand on this example).我在示例中显示的期望结果(它不是真实的,但理解这个示例会很有用)。
I've used CONCAT but it does't create new column, just concatenation.我使用过 CONCAT 但它不会创建新列,只是连接。 How do I get:
如何得到:
id Col1 Col2
1 foo 10
2 bar 42
3 baz 14
to到
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
check the live demo here https://www.db-fiddle.com/f/sNANpwdUPdJfUaSQ77MQUM/1在此处查看现场演示https://www.db-fiddle.com/f/sNANpwdUPdJfUaSQ77MQUM/1
and read docs here https://www.postgresql.org/docs/current/functions-string.html并在此处阅读文档https://www.postgresql.org/docs/current/functions-string.html
And do not forget about null values并且不要忘记 null 值
But if you want to create a really new column in the table as a result of concatenation:但是如果你想在表中创建一个真正的新列作为连接的结果:
alter table t
add column NewColumn text
GENERATED ALWAYS AS (
coalesce(col1, '') || ': ' || coalesce(col2::text, '')
) STORED;
select id, NewColumn FROM t
Check the live demo here https://www.db-fiddle.com/f/sNANpwdUPdJfUaSQ77MQUM/2在此处查看现场演示https://www.db-fiddle.com/f/sNANpwdUPdJfUaSQ77MQUM/2
And documentation https://www.postgresql.org/docs/current/ddl-generated-columns.html和文档https://www.postgresql.org/docs/current/ddl-generated-columns.html
You can use below statement,您可以使用以下语句,
select id, Col1||': '||Col2 as NewColumn from table_name;
In order to get Col1 and Col2 as well, you can use below,为了同时获得 Col1 和 Col2,您可以在下面使用,
select id, Col1, Col2, Col1||': '||Col2 as NewColumn from table_name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.