SQL如何按客户ID分组生成逗号分隔的产品编码列表
SQL调整方案
你当前的查询直接返回两表关联后的全量明细,所以会出现一对多关系下客户信息重复、每个产品占一行的情况,只需要通过字符串聚合函数按客户维度分组,即可实现单客户对应逗号分隔产品编码列表的效果。
不同数据库的字符串聚合函数存在差异,可根据你使用的数据库选择对应写法:
MySQL 环境(5.x及以上版本通用)
使用GROUP_CONCAT函数完成字符串拼接,代码如下:
SELECT Customer.Ids AS Customer_ids, Customer.姓名, Customer.性别, Customer.年龄, Customer.联系电话, GROUP_CONCAT(Product.productcode SEPARATOR ',') AS productcode_list FROM Customer INNER JOIN Product ON Customer.Ids = Product.CustomerId GROUP BY Customer.Ids, Customer.姓名, Customer.性别, Customer.年龄, Customer.联系电话;
PostgreSQL / SQL Server 2017及以上 / SQLite 3.30及以上环境
使用标准SQL的STRING_AGG函数完成拼接,代码如下:
SELECT Customer.Ids AS Customer_ids, Customer.姓名, Customer.性别, Customer.年龄, Customer.联系电话, STRING_AGG(Product.productcode, ',') AS productcode_list FROM Customer INNER JOIN Product ON Customer.Ids = Product.CustomerId GROUP BY Customer.Ids, Customer.姓名, Customer.性别, Customer.年龄, Customer.联系电话;
Oracle 环境(11gR2及以上版本)
使用LISTAGG函数完成拼接,代码如下:
SELECT Customer.Ids AS Customer_ids, Customer.姓名, Customer.性别, Customer.年龄, Customer.联系电话, LISTAGG(Product.productcode, ',') WITHIN GROUP (ORDER BY Product.ids) AS productcode_list FROM Customer INNER JOIN Product ON Customer.Ids = Product.CustomerId GROUP BY Customer.Ids, Customer.姓名, Customer.性别, Customer.年龄, Customer.联系电话;
注意事项
- GROUP BY子句需要包含所有SELECT后未做聚合的客户基础字段,否则在开启全组校验(如MySQL的
ONLY_FULL_GROUP_BY模式)的环境中会抛出语法错误 - 如果需要对拼接的产品编码去重,可以在聚合函数内加DISTINCT关键字,例如
GROUP_CONCAT(DISTINCT Product.productcode SEPARATOR ',') - 如果需要按指定顺序排列拼接的产品编码,可以在聚合逻辑中增加排序规则,例如MySQL中可以写
GROUP_CONCAT(Product.productcode ORDER BY Product.售价 DESC SEPARATOR ',')
内容的提问来源于stack exchange,提问作者Руслан Пилипюк
相关产品推荐
相关产品推荐

