基于PostgreSQL中的列向列数据追加文本

基于PostgreSQL中的列向列数据追加文本,postgresql,Postgresql,我想在表中每列的每个单元格中添加一些文本,作为该列的符号。例如,假设我的表格如下所示(所有字段的类型都不同): 姓名年龄地点 詹姆士45法国 西蒙33美国 本76中国 我想将其修改为: name age location ajames b45 cfrance asimon b33 cusa aben b76 cchina 姓名年龄地点 阿贾姆斯b45法国 asimon b33 cusa 阿本b76中国 有人对我如何做到这一点有什么建议吗?首先,

我想在表中每列的每个单元格中添加一些文本,作为该列的符号。例如,假设我的表格如下所示(所有字段的类型都不同):

姓名年龄地点 詹姆士45法国 西蒙33美国 本76中国 我想将其修改为:

name age location ajames b45 cfrance asimon b33 cusa aben b76 cchina 姓名年龄地点 阿贾姆斯b45法国 asimon b33 cusa 阿本b76中国
有人对我如何做到这一点有什么建议吗?

首先,你必须把你的年龄变成某种类型的字符串。之后,您可以像这样转换值(当然,您必须对每个字段执行此操作):

这将更新表中的数据。如果您只希望输出带有前缀,则可以使用以下方法:

select 'a' || name as name, 'b' || age as age from mytable;

在这种情况下,不需要转换年龄数据类型。

接受的答案是不处理空值和空格。所以我给出了这个答案。如果它能帮助别人,那将是我的荣幸

update "public"."mytable" set 
"name"= case when "name" is null or trim("name")='' then null else 'a' || "name" end,
"age"= case when "age" is null or trim("age")='' then null else 'b' || "age" end,
"location"= case when "location" is null or trim("location")='' then null else 'c' || "location" end;

这是因为我知道我想用字母来表示数据,因为我将在表上执行某种数据挖掘,而我的数据挖掘代码采用字符串。很抱歉,使用答案提问,但有没有办法在答案1中反转过程?(无法评论)。因为我执行了更新,但在where子句中,我错贴了“类似于”运算符的值,它将文本添加到所有条目中。谢谢谢谢,这似乎就是我要找的!如果列的初始值为null,则该函数不起作用:(你说的“不起作用”是什么意思?有错误消息吗?如果你正在寻找不同的行为,你可以尝试concat函数:如果该值为null,有任何建议吗?@Sebastianvommer谢谢。是的,用concat_ws(…)和COALESCE(…)进行了尝试。这些解决了我的问题。
select 'a' || name as name, 'b' || age as age from mytable;
update "public"."mytable" set 
"name"= case when "name" is null or trim("name")='' then null else 'a' || "name" end,
"age"= case when "age" is null or trim("age")='' then null else 'b' || "age" end,
"location"= case when "location" is null or trim("location")='' then null else 'c' || "location" end;