I'm working in SQL Server 2014, and I have the following simple data, which tracks calling history of users:
PhoneNumber Activity ActivityDate
------------------------------------
9075551234 Incoming 2022-04-01
9075551234 Outgoing 2022-04-06
9075551234 Outgoing 2022-04-10
9075551234 Outgoing 2022-08-02
9075551234 Incoming 2022-08-05
9075551234 Lateral 2022-08-10
5551239876 Incoming 2022-07-01
5551239876 Outgoing 2022-07-06
5551239876 Outgoing 2022-08-01
5551239876 Outgoing 2022-08-02
5551239876 Incoming 2022-08-15
I need to group the ACTIVITY values into one field, which effortlessly be done using the STUFF FOR XML function:
phonenumber FirstContact LatestContact Result
------------------------------------------------------------------
5551239876 2022-07-01 2022-08-15 Incoming,Outgoing,Outgoing,Outgoing,Incoming
9075551234 2022-04-01 2022-08-10 Incoming,Outgoing,Outgoing,Outgoing,Incoming,Lateral
However I need to conditionally group these, on the condition that there was more than a 90 day between the activity date. Desired result:
phonenumber FirstContact LatestContact Result
-------------------------------------------------------------------
9075551234 2022-04-01 2022-04-10 Incoming,Outgoing,Outgoing
9075551234 2022-08-02 2022-08-10 Outgoing,Incoming,Lateral
5551239876 2022-07-01 2022-08-15 Incoming,Outgoing,Outgoing,Outgoing,Incoming
Here's the code/sample values I'm using, thanks!
DECLARE @separator CHAR(1) = ',';
WITH testTable (PhoneNumber,Activity,ActivityDate) as
(
SELECT 9075551234 , 'Incoming' , '2022-04-01' UNION ALL
SELECT 9075551234 , 'Outgoing' , '2022-04-06' UNION ALL
SELECT 9075551234 , 'Outgoing' , '2022-04-10' UNION ALL
SELECT 9075551234 , 'Outgoing' , '2022-08-02' UNION ALL
SELECT 9075551234 , 'Incoming' , '2022-08-05' UNION ALL
SELECT 9075551234 , 'Lateral' , '2022-08-10' UNION ALL
SELECT 5551239876 , 'Incoming' , '2022-07-01' UNION ALL
SELECT 5551239876 , 'Outgoing' , '2022-07-06' UNION ALL
SELECT 5551239876 , 'Outgoing' , '2022-08-01' UNION ALL
SELECT 5551239876 , 'Outgoing' , '2022-08-02' UNION ALL
SELECT 5551239876 , 'Incoming' , '2022-08-15'
)
SELECT p.phonenumber
, min(activitydate) FirstContact
,max(activitydate) LatestContact
, STUFF((SELECT @separator + Activity
FROM testTable AS c
WHERE c.phonenumber = p.phonenumber
FOR XML PATH('')), 1, LEN(@separator), '') AS Result
FROM testTable AS p
GROUP BY p.phonenumber
ORDER BY p.phonenumber;