多行进入单一SQL

时间:2017-05-24 21:50:55

标签: sql sql-server tsql

我正在寻找下一个例子的解决方案:

Example

我想要的是:

Check Type | Date       | Retailer | Value                    | Count

Duplicated | 2017-05-01 | SAMCO1   | 4742,4749,4853,6781,7658 | 5

Duplicated | 2017-05-02 | SAMCO1   | 4742,4749,4853,6781,7658 | 5

1 个答案:

答案 0 :(得分:1)

使用common table expressionstuff() with select ... for xml path ('') method of string concatenation

;with cte as (
  select 
      MMC.CheckType
    , PR.ModifiedDate
    , MMC.RetailerID
    , AttributeValue
    , COUNT(*) as MissingCount
  from MissingMappingCheck MMC
    inner join LastProcessRun PR 
      on PR.ProcessRunID = MMC.ProcessRunId
  group by 
      MMC.CheckType
    , PR.ModifiedDate
    , MMC.RetailerID
    , AttributeValue
)
select 
    CheckType
  , ModifiedDate
  , RetailerId
  , AttributeValues = stuff((
      select ','+i.AttributeValue 
      from cte as i
      where i.CheckType = t.CheckType
        and i.ModifiedDate = t.ModifiedDate
        and i.RetailerId = t.RetailerId
      order by i.AttributeValue
      for xml path (''), type).value('.','nvarchar(max)')
      ,1,1,'')
  , MissingCount = sum(MissingCount)
from cte t
group by CheckType, ModifiedDate, RetailerId
order by 
    CheckType
  , RetailerID
  , ModifiedDate