SQL查询 - 如果另外2列相等,则合并由逗号分隔的2列结果

时间:2018-05-01 07:57:42

标签: sql merge

我需要有关SQL查询的帮助才能执行以下操作 - > 如果除了sku_num之外的Column结果相等,则将sku_num组合并用逗号分隔。此示例仅有2个结果,但可能有2个以上的结果。提前谢谢

我有

的结果

![在此处输入图片说明] [1]

我需要的结果

[![我需要的结果] [2]] [2]

SQL代码

SELECT chassis_option.chassis_id          AS [Chassis ID], 
       chassis_option.module_id           AS [Module ID], 
       chassis_option.internal_name       AS [Option Internal Name], 
       chassis_option.global_option_id    AS [Global Option ID], 
       chassis_option.option_code         AS [Regional Option ID], 
       chassis_option.external_name       AS [Option External Name], 
       chassis_option.current_status_code AS [Option Status], 
       chassis_option_item.sku_num 
FROM   chassis_option 
       INNER JOIN chassis_option_item 
               ON chassis_option.chassis_id = chassis_option_item.chassis_id 
                  AND chassis_option.module_id = chassis_option_item.module_id 
                  AND chassis_option.option_code = 
                      chassis_option_item.option_code 
WHERE  ( chassis_option.global_option_id = N'GJP0LCK' ) 

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT <list all columns>, group_concat(sku_num) sku_num
FROM tableName
GROUP BY <list all columns>

SQL Server

SELECT 
    <list all columns>, 
    STRING_AGG(sku_num, ',') WITHIN GROUP (ORDER BY sku_num) AS [sku_num]
FROM 
    tableName
GROUP BY 
    <list all columns>

P.S。 SELECTGROUP BY中的列列表应相同。