SQL STUFF函数汇总了多行

时间:2017-07-19 17:58:30

标签: sql-server tsql string-aggregation

我正在尝试在同一天制作条目时合并一个字段。用户可以在同一天为给定的源多次输入消息。结果表如下 -

enter image description here

我想要做的是在同一天为MessageText组合SourceID一个条目。

我知道它会为SourceID和同一天创建记录,但无论日期是什么,它都会为MessageText设置每个SourceID。它确实在同一天给出了一行。例如,SourceID在2012-11-08的2017-07-11上有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

3 个答案:

答案 0 :(得分:1)

使用stuff()时要记住,它需要四个参数stuff(Query for xml path(''),1,1,'')。您可以使用诸如此类的stuff()-

stuff((select +'/'+(CASE WHEN t2.Name IS NOT NULL THEN t2.Name ELSE (ISNULL(t2.FirstName,'') + ' ' + ISNULL(t2.LastName,'')) END)
                  from table2 t2 inner join table1 MR on t2.id = mr.id
                  where t2.ContactId = m2.contactid for xml path('')),1,1,'')

答案 1 :(得分: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);

答案 2 :(得分: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);