let me show you my code.

THIS is my function
 That return me date time .

```
  ALTER FUNCTION GoldenMemebr(@clubid uniqueidentifier ) returns datetime
  WITH SCHEMABINDING
   as
  begin
 DECLARE @TEMP TABLE 
 (
 TRANSTIME DATETIME,
 TOTSCORE  BIGINT,
 CLUBID uniqueidentifier
 )
INSERT INTO @TEMP (CLUBID,TRANSTIME,TOTSCORE)

 SELECT ClubProfileId, TransactionTimeStamp, 
 SUM(Points) OVER (ORDER BY TransactionTimeStamp) totalamount 
 FROM  
  dbo.CardTransaction CT
 inner join dbo.CardTransactionLog CL 
 on CL.CardTransactionLogId =   CT.CardTransactionLogId
 and ClubProfileId = @clubid

  order by CL.TransactionTimeStamp 

declare @ti datetime
set @ti = 
(
 SELECT top 1 TRANSTIME  
 FROM @TEMP 
WHERE TOTSCORE >= 12000 
order by TRANSTIME asc

)
 return @ti
 end

```

and this is my Query

```
select FirstName,LastName,
SUM(Points) as score,   dbo.GoldenMemebr(cp.ClubProfileId) as ExactTime 
from ClubProfile cp join CardTransaction ct
on ct.ClubProfileId = cp.ClubProfileId
where MembershipType = 1
group by FirstName,LastName,dbo.GoldenMemebr(cp.ClubProfileId)

```

this query take 14 sec for 38 records(it is terrible)

how can i optimized that ?