You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:36:14