选择具有不同名称的不同ID,并选择与所选ID相关的名称:/

问题描述 投票:0回答:1

我的头衔听起来像绕口令,所以让我更好地解释一下自己。我有一个数据质量非常差的表,其中有以下情况:

CustomerId CustomerName
1          Jhon
1          Mary
2          Tom 

CustomerId不是表的键。

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

select distinct CustomerId, CustomerName from FullTransactions

它返回了先前的数据集,然后当我尝试填充组合框时,由于不允许重复相同的键而引发了异常。

您是否建议采取任何变通方法以使选择与众不同,以返回唯一的customerId,我不介意是只选择其中一种客户名,还是每次出现时都将其合并为一个名称...

CustomerId CustomerName
1          Jhon-Mary
2          Tom 

希望我现在能更好地解释自己...非常感谢您为我们带来的光明...

sql-server select distinct
1个回答
0
投票

在SQL Server 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;
© www.soinside.com 2019 - 2024. All rights reserved.