T-SQL to concatenate multiple rows of DateTime column

Problem 

I need to concatenate the following EventDate (latest to oldest) into a single row grouped by ParentWebGuid on Microsoft SQL 2008 R2 database view:

SELECT   TOP (100) PERCENT ParentWebGuid, TypeOfEvent, CONVERT(VARCHAR(10), EventDate, 103) AS EventDateString
FROM     dbo.SupervisionEvent
WHERE    (TypeOfEvent = 'Visit [P]RP')
ORDER BY ParentWebGuid, EventDate DESC



Solution

SELECT DISTINCT TOP (100) PERCENT ParentWebGuid, REPLACE
((SELECT TOP (100) PERCENT CONVERT(VARCHAR(10), EventDate, 103) AS 'data()'
FROM dbo.SupervisionEvent
WHERE (TypeOfEvent = 'Visit [P]RP') AND (ParentWebGuid = mainTable.ParentWebGuid)
ORDER BY EventDate DESC FOR XML PATH('')), ' ', ', ') AS VisitPrpEventDates
FROM dbo.SupervisionEvent AS mainTable
WHERE (TypeOfEvent = 'Visit [P]RP')


Explanation

AS 'data()' to eliminate column name being displayed as result

WHERE (TypeOfEvent = 'Visit [P]RP') to limit result to certain TypeOfEvent on both main and sub-query.

FOR XML PATH('') to output as concatenated string separated by space

REPLACE(, ' ', ', ') solved my problem very well as the concatenated date string is separated by by space and can be replaced in this case with a comma and space which can be any separator string.

Hopefully this note will help me and you in the future if we encounter similar problem using T-SQL (Transact-SQL for Microsoft SQL Server)

Comments

Popular posts from this blog

How to search Active Directory group members using Windows 10 built-in tools

How to check and reload PAC (Proxy Auto Configuration) file on Windows