2017-03-23 85 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 
相關問題