2017-07-19 99 views
0

我試圖在同一天輸入項目時合併一個字段。用戶可以在同一天爲給定的源多次輸入消息。結果表是繼 -SQL STUFF函數彙總多行

enter image description here

我想這樣做的是使一個項目在同一天爲SourceID結合MessageText

我已經在哪裏創建了SourceID和當天的記錄,不過無論日期如何,它都會爲該SourceID放置每個MessageText。它確實在同一天給出一行。例如,SourceID在2017年11月11日的2012-11-08上有2個條目。它爲2012-11-08創建了一行,2017-07-11創建了一個行,但是它將所有3 MessageText排在同一行。

enter image description here

我的代碼 -

SELECT distinct s.SourceID, stuff ((select ', ' + rtrim(x.MessageText) 
              from [AVData].[dbo].[LogCentralMessageData] x 
              inner join AVData.[dbo].[Source] a on a.SourceID = t.SourceID 
              inner join(select distinct max(m.CreatedOn)over (partition by r.SourceSiteID, Convert(date, m.CreatedOn)) as maxDate, r.SourceSiteID 
               from [AVData].[dbo].[LogCentralMessageData] m 
               left join AVData.[dbo].[Source] r on r.SourceID = m.SourceID 
               ) t on t.SourceSiteID = a.SourceSiteID and convert(date, t.maxDate) = Convert(date, x.CreatedOn) 

              where x.SourceID = a.SourceID 

              for XML path('')), 1, 1, '') message_text 
     ,convert(date, t.CreatedOn) as CreatedDate 


from [AVData].[dbo].[LogCentralMessageData] t 

left join AVData.[dbo].[Source] s on s.SourceID = t.SourceID 
order by SourceID, CreatedDate 

回答

0

下應該做的伎倆......

SELECT 
    st1.SourceID, 
    CAST(st1.CreatedOn AS DATE) 
    message_text = STUFF(
       (SELECT 
        CONCAT(', ', st2.MessageText) 
       FROM 
        dbo.SomeTable st2 
       WHERE 
        st1.SourceID = st2.SourceID 
        AND CAST(st1.CreatedOn AS DATE) = CAST(st2.CreatedOn AS DATE) 
       ORDER BY 
        st2.CtreatedOn 
       FOR XML PATH ('') 
       ), 1, 2, '') 
FROM 
    dbo.SomeTable st1 
GROUP BY 
    st1.SourceID, 
    CAST(st1.CreatedOn AS DATE); 
+0

由於某些原因,它無法識別以'st1.'開頭的任何內容,然後我得到 - 關鍵字FOR –

+0

附近的語法錯誤,它在CAST語句後缺少「,」。當我把這些陳述落實到位時,謝謝! –

+0

好的交易,很高興它會爲你工作。 –

0
SELECT SourceID, cast(CreatedOn as date) as CreatedDate, message_text = STUFF(
      (SELECT ',' + MessageText 
       FROM yourtable t1 
       WHERE t1.id = t2.id 
       FOR XML PATH ('')) 
      , 1, 1, '') from yourtable t2 
group by SourceID, cast(CreatedOn as date); 
+0

我收到了同樣的結果,因爲我之前做過。 –