You should be able to re-use the same variable that lets you pick your columns, like this:
create procedure dynamic_group_by (@params nvarchar(max))
declare @sql nvarchar(max)
set @sql = 'select ' + @params + ' from profiles p
where email like ''%@%''
group by ' + @params
exec sp_executesql @sql
You want to do a LATERAL join, by putting the the function in the FROM list. If you just put the function in the from list after table "a", you don't need the LATERAL keyword, as joins to functions are automatically lateral. If you wrap it in a dummy "select * from", then you do need the keyword:
WITH A AS (SELECT DISTINCT trip_id FROM stop_times)
If the gap between matches is always more than 3 days, you could use this:
;WITH CTE AS
CASE WHEN DATEDIFF(day,LAG(DateField) OVER(ORDER BY DateField),DateField)> 3 THEN 1 ELSE 0 END as newround,
SELECT Datefield, HomeTeam,AwayTeam, SUM(newround) OVER(ORDER BY DateField) +...