I've got a table something like this:
UserID TeamID StartedDate
36202 1213 27/11/2019 9:00
36203 1213 1/11/2019 10:30
36203 1207 24/11/2019 10:00
36205 1207 21/11/2019 9:15
36203 1213 1/11/2019 10:30
36214 1217 10/11/2019 10:00
36205 1207 24/11/2019 10:00
36202 1213 1/11/2019 10:30
How do I query a list of users who have the same "StartedDate" for each unique date?
Output should be look like this.
StartedDate UserID's
24/11/2019 10:00 36203 & 36205
1/11/2019 10:30 36202 & 36203
I need to ignore time & focus on the date only.
You can achieve it by this way, Live demo here
SELECT DISTINCT C2.StartedDate,
SUBSTRING(
(
SELECT ', ' + CAST(C1.UserID AS VARCHAR(20))
FROM TempTable C1
WHERE C1.StartedDate = C2.StartedDate
ORDER BY C1.StartedDate
FOR XML PATH ('')
), 2, 1000) AS "UserList"
FROM TempTable C2
Output
StartedDate UserList
1/11/2019 10:30 36203, 36203, 36202
10/11/2019 10:00 36214
21/11/2019 9:15 36205
24/11/2019 10:00 36203, 36205
27/11/2019 9:00 36202
Try this:
DECLARE @DataSource TABLE
(
[UserID] INT
,[TeamID] INT
,[StartedDate] VARCHAR(24)
);
INSERT INTO @DataSource ([UserID], [TeamID], [StartedDate])
VALUES (36202, 1213, '27/11/2019 9:00')
,(36203, 1213, '1/11/2019 10:30')
,(36203, 1207, '24/11/2019 10:00')
,(36205, 1207, '21/11/2019 9:15')
,(36203, 1213, '1/11/2019 10:30')
,(36214, 1217, '10/11/2019 10:00')
,(36205, 1207, '24/11/2019 10:00')
,(36202, 1213, '1/11/2019 10:30');
-- SQL Server 2017+
SELECT [StartedDate]
,STRING_AGG([UserID], ',') AS [UserID's]
FROM
(
SELECT DISTINCT [StartedDate]
,[UserID]
FROM @DataSource
) DS
GROUP BY [StartedDate];
-- SQL Server
WITH DataSoruce AS
(
SELECT DISTINCT [StartedDate]
FROM @DataSource
)
SELECT *
FROM DataSoruce A
CROSS APPLY
(
SELECT STUFF
(
(
SELECT DISTINCT ',' + CAST([UserID] AS VARCHAR(12))
FROM @DataSource S
WHERE A.[StartedDate] = S.[StartedDate]
FOR XML PATH, TYPE
).value('.', 'VARCHAR(MAX)')
,1
,1
,''
)
) R ([UserID's])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With