【发布时间】:2017-07-19 17:58:29
【问题描述】:
我正在尝试在同一天进行条目时合并一个字段。用户可以在同一天为给定的源多次输入消息。结果表如下 -
我想做的是在同一天将MessageText 与SourceID 组合在一起。
我有它,它将在同一天为SourceID 创建一个记录,但是无论日期是什么,它都会为该SourceID 放置每个MessageText。它确实为同一天提供一排。例如,SourceID 在 2012 年 11 月 8 日有 2 个条目,在 2017 年 7 月 11 日有 1 个条目。它为 2012-11-08 创建一行,为 2017-07-11 创建一个行,但是它将所有 3 个 MessageText 放在行中。
我的代码是 -
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
【问题讨论】:
标签: sql-server tsql string-aggregation