select 具有不同名称的不同 ID,select 还有与 ID selected 相关的名称:/

select distinct Id with different names asociated and select also the names related to the id selected :/

我的标题听起来像是绕口令,所以让我更好地解释一下。我有一个 table 的数据质量非常差,我有以下情况:

CustomerId CustomerName
1          Jhon
1          Mary
2          Tom 

CustomerId 不是 table 的键。

我需要用列表填充字典,但是当我执行以下操作时:

select distinct CustomerId, CustomerName from FullTransactions

它 return 编辑了以前的数据集,然后当我尝试填充组合框时出现异常,因为我不允许重复相同的键。

您是否建议任何解决方法来使 select 与众不同,其中 return 是唯一的客户 ID,我不介意 select 只是其中一个客户名称或合并在一个名字中每次出现...

CustomerId CustomerName
1          Jhon-Mary
2          Tom 

希望我现在能更好地解释自己... 提前非常感谢您带来的任何光线...

在SQLServer 2017中,可以使用聚合函数string_agg():

select 
    CustomerId , 
    string_agg(CustomerName, '-') within group (order by CustomerName) CustomerName
from mytable
group by CustomerId 

在早期版本中,解决方案是使用for xml pathstuff()

select distinct 
    t.CustomerId,
    stuff(
        (
            select distinct ',' + t1.CustomerName
            from mytable t1
            where t1.CustomerId = t.CustomerId
            for xml path(''), type
        ).value('.', 'nvarchar(max)'),
        1,
        0,
        ''
    ) CustomerName
from mytable t;