2017-03-23 6 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で

  • をサーバー、never use長さのない(または関連するタイプ)。コンテキストはデフォルトによって異なり、実際には見つけにくいバグを(潜在的に)導入しています。
  • コンマの後ろにスペースがあるため、stuff()には2つの文字(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

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 
関連する問題