SQL Server query takes too long to execute. What could the problem be?
Thank you for your effort and suggestions. Here is the solution which took only 6 minutes to execute:

WITH T1
AS (
    SELECT FileCode
        ,dbo.GetLastDayOfMonth(left(f.FileFormationDate, 4), substring(f.FileFormationDate, 6, 2)) AS Datekey
    FROM [StageArea].[Sales].[viwLossCalculation] f
    GROUP BY FileCode
        ,dbo.GetLastDayOfMonth(left(f.FileFormationDate, 4), substring(f.FileFormationDate, 6, 2))
    )
    ,T2
AS (
    SELECT dbo.GetLastDayOfMonth(c.Year, c.Monthkey) AS datekey2
        ,ComplaintCount AS complaintcount
    FROM [StageArea].[Preservation].[viwComplaint] c
    )
SELECT C.DateKey
    ,f.complaintcount
    ,COUNT(DISTINCT c.FileCode) AS FileCodeCount
FROM T1 C
INNER JOIN T2 F ON C.DateKey = F.DateKey2
GROUP BY C.DateKey
    ,f.ComplaintCount;