2017-03-23 52 views
1

基于这里的问题概括的方法不同:使用带的东西/ XML的路径(“”)

Concatenate many rows into a single text string?

我想放在一起的连接字符串唯一的值。我的代码是目前:

select rc.Routage 
    , COUNT(distinct rc.Event) 
    , STUFF((select ', ' + cast(rcA.Event as varchar) 
      from Receiving rcA 
      where rcA.supplier = 'user' 
       and rcA.DATETIME > '20170322' 
       and rc.Routage=rcA.Routage 
      for xml path('')) 
     , 1, 1, '') 
from Receiving rc 
where rc.supplier = 'user' 
    and rc.DATETIME > '20170322' 
group by rc.Routage 
order by COUNT(distinct rc.Event)desc 

这给了我,我期望的输出,但我想/消除的东西重复值XML路径字段。

我已经试过了stuff/xml部分中的distinctgroup by的各种组合,但无法正确拼合在一起。

为了澄清,对于COUNT(distinct rc.Event) = 2,我希望从stuff子句中看到2个不同的事件。我怎样才能做到这一点?

回答

4

使用select distinct子查询:

select rc.Routage, 
     count(distinct rc.Event), 
     stuff((select distinct ', ' + cast(rcA.Event as varchar(max)) 
       from Receiving rcA 
       where rcA.supplier = 'user' and 
        rcA.DATETIME > '20170322' and 
        rc.Routage = rcA.Routage 
       for xml path('') 
      ), 1, 2, '') 
from Receiving rc 
where rc.supplier = 'user' and rc.DATETIME > '20170322' 
group by rc.Routage; 

注:

  • 在SQL服务器,从不使用varchar()(或相关类型)没有长度。默认情况因上下文而异,并且您(可能)引入了一个很难找到的错误。
  • 您希望stuff()删除两个字符,而不是1,因为您的逗号后跟一个空格。
  • 该公式假定Event没有XML特殊字符。如果这是一个问题,很容易调整。

而且,这种类型的查询通常更快,如果你消除子查询的副本:

select rc.Routage, rc.numEvents, 
     stuff((select distinct ', ' + cast(rcA.Event as varchar(max)) 
       from Receiving rcA 
       where rcA.supplier = 'user' and 
        rcA.DATETIME > '20170322' and 
        rc.Routage = rcA.Routage 
       for xml path(''), type 
      ).value('.', 'varchar(max)' 
        ), 1, 2, '' 
      ) 
from (select rc.Routage, count(distinct rc.Event) as numEvents 
     from Receiving rc 
     where rc.supplier = 'user' and rc.DATETIME > '20170322' 
     group by rc.Routage 
    ) rc; 
+0

尼斯。也感谢您的其他指针 - 它们已被考虑在内。多谢。 – User632716

2

执行distinct在子查询中,XML处理的任何地方快要到它之前:

select rc.Routage 
    , COUNT(distinct rc.Event) 
    , STUFF((select ', ' + cast(rcA.Event as varchar) 

      from (select distinct Event from Receiving a 
        where supplier = 'user' 
        and DATETIME > '20170322' 
        and rc.Routage=a.Routage 
      ) rcA 

      for xml path('')) 
     , 1, 1, '') 
from Receiving rc 
where rc.supplier = 'user' 
    and rc.DATETIME > '20170322' 
group by rc.Routage 
order by COUNT(distinct rc.Event)desc 
相关问题