SQL Server High Hash Match and Sort
First of all true test of sql is to take variable instead of constant value.
So ,

Declare @From date='2017-10-01' 
Declare @To date='2018-09-30'


Immediate correction ,put the filter here

select
g.*,
a.StateId, 
a.CountryId
into #Temp
from #TempGuidelineLog g
JOIN [vwCustomerAddress] a ON a.CustomerId = g.CustomerId
where g.CountryId = 1 and g.StateId NOT IN (65,66)


and remove the same filter from where it is now.

I see no requirement of LogDate in #TempGuidelineLog so remove it.

so new index,

CREATE NONCLUSTERED INDEX ix_temp1Customer ON #TempGuidelineLog (CustomerId)


Since countryid is more selective,

CREATE NONCLUSTERED INDEX ix_temp1Country ON #Temp (CountryId,Stateid,CustomerId)

CREATE NONCLUSTERED INDEX ix_temp1Country ON #Temp (CustomerId)


IMO, group by St.Name and co.Name is also hurting your performance.

so you can seperatly query group by function and then with that resultset join State and country table.hope it is clear.

The way you are creating XML is also complicated.You can choose one of the xml design which suite you from here,XML