2017-05-24 62 views
-1

我尋找下一個例子的解決方案:多行成單一個SQL

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 
+2

你的邏輯是什麼? –

+0

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 ORDER BY MMC.CheckType,MMC.RetailerID, PR.ModifiedDate這是我使用的代碼 –

+1

請閱讀http://meta.stackoverflow.com/questions/285551/爲什麼我可以不要上傳圖像的代碼的時候提出問題/ 285557和接受的答案 –

回答

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