使用distinct with stuff / for xml path('')

时间:2017-03-23 11:44:44

标签: sql sql-server-2008

基于此处问题中概述的方法:

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

这给了我期望的输出,但是我想消除stuff / for xml path字段中的重复值。

我在stuff / xml部分尝试了distinctgroup by的各种组合,但无法将它们正确地拼凑在一起。

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

2 个答案:

答案 0 :(得分:6)

在子查询中使用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 Server中,从不使用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;

答案 1 :(得分:2)

在XML处理到达任何地方之前,在子查询中执行distinct

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