如何在SQL查询中将联系人名与姓合并至同一列?
合并联系人姓名的SQL查询方案
要将contactfirstname(名)与contactlastname(姓)合并到同一列,不同数据库有不同的字符串拼接实现方式,以下是适配你需求的修改方案:
通用兼容写法(适配MySQL、PostgreSQL、SQL Server 2012+、Oracle 11g+)
使用CONCAT()函数拼接字段,中间添加空格分隔姓名,同时通过AS指定列别名方便识别:
SELECT customernumber, customername, CONCAT(contactfirstname, ' ', contactlastname) AS contactfullname FROM dbs211_customers WHERE country = 'Canada' ORDER BY customernumber;
分数据库特殊写法
- Oracle旧版本:可使用
||运算符完成字符串拼接:
SELECT customernumber, customername, contactfirstname || ' ' || contactlastname AS contactfullname FROM dbs211_customers WHERE country = 'Canada' ORDER BY customernumber;
- SQL Server 2012之前版本:使用
+运算符拼接,若字段可能存在NULL值,需用ISNULL()处理避免整列结果为空:
-- 字段无NULL值时的基础写法 SELECT customernumber, customername, contactfirstname + ' ' + contactlastname AS contactfullname FROM dbs211_customers WHERE country = 'Canada' ORDER BY customernumber; -- 处理NULL值的安全写法 SELECT customernumber, customername, ISNULL(contactfirstname, '') + ' ' + ISNULL(contactlastname, '') AS contactfullname FROM dbs211_customers WHERE country = 'Canada' ORDER BY customernumber;
内容的提问来源于stack exchange,提问作者Anish Budha
相关产品推荐
相关产品推荐

