Question: I need help Please.I have a query that was inserted into two different temp table. How can i rewrite the query again to avoid the use of temp table.
For example, 

```
declare @sdate as datetime
declare @edate as datetime

set @sdate = '01-Apr-2016 00:00:00'
set @edate = '31-Mar-2017 23:59:59'

/*Falls*/
Select
    DISTINCT
    R.ID
    ,C.EmpNo
Into #FALLS
from
    tableA as R
    left join  tableB as C
    on R.ID = C.ID
where
    R.[dateTime] between @sdate and @edate 
/*Phys  */
Select
    DISTINCT
    A.ID
    ,(A.ActualTime) as [DateTime]
    ,A.SeqID 
into #Physio
from
    tableC as A
    left join #FALLS as Falls
    on Falls.ID = A.ID 

/* COMBINE RESULT */
Select
    P1.ID
    ,P1.EmpNo
    ,P1.SeqID   
from
    (Select
        DISTINCT
        Falls.ID
        ,Falls.EmpNo
        ,MIN(Physio.[DateTime])         
    from
        #FALLS as Falls
        left join #Physio as Physio
        on Falls.ID = Physio.ID 

    group by
        Falls.ID
        ,Falls.EmpNo
    ) as P1
    left join #Physio as P2
    on P1.ID = P2.ID 

```

How can i rewrite the sql without using temp tables.

Answer: 
I don't see the problem with using temp tables, but you can use a two `CTE`s instead:

```
DECLARE @sdate AS DATETIME
DECLARE @edate AS DATETIME

SET @sdate = '01-Apr-2016 00:00:00'
SET @edate = '31-Mar-2017 23:59:59'

;WITH Falls
AS (
    SELECT DISTINCT R.ID
        ,C.EmpNo
    FROM tableA AS R
    LEFT JOIN tableB AS C ON R.ID = C.ID
    WHERE R.[dateTime] BETWEEN @sdate
            AND @edate
    )
    ,Physio
AS (
    SELECT DISTINCT A.ID
        ,(A.ActualTime) AS [DateTime]
        ,A.SeqID
    FROM tableC AS A
    LEFT JOIN Falls AS Falls ON Falls.ID = A.ID
    )
SELECT P1.ID
    ,P1.EmpNo
    ,P1.SeqID
FROM (
    SELECT DISTINCT Falls.ID
        ,Falls.EmpNo
        ,MIN(Physio.[DateTime])
    FROM Falls AS Falls
    LEFT JOIN Physio AS Physio ON Falls.ID = Physio.ID
    GROUP BY Falls.ID
        ,Falls.EmpNo
    ) AS P1
LEFT JOIN Physio AS P2 ON P1.ID = P2.ID

```
the query below should bring the same result.
also this looks like a homework question.

```
declare @sdate as datetime
declare @edate as datetime

set @sdate = '01-Apr-2016 00:00:00'
set @edate = '31-Mar-2017 23:59:59'

Select  DISTINCT
        R.ID
        ,C.EmpNo
        ,MIN(Physio.ActualTime) SeqID        
    from
        tableA as R
    left join  tableB as C
       on R.ID = C.ID   
        left join tableC as Physio
        on Falls.ID = Physio.ID 
where
    R.[dateTime] between @sdate and @edate 

GROUP BY   R.ID
        ,C.EmpNo

```