如何将temp表的查询重写为子查询或在sql中加入

时间:2016-06-08 18:29:40

标签: sql

我需要帮助Please.I有一个插入两个不同临时表的查询。如何重新重写查询以避免使用临时表。 例如,

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 

如何在不使用临时表的情况下重写sql。

2 个答案:

答案 0 :(得分:1)

我没有看到使用临时表的问题,但您可以改为使用两个CTE

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

答案 1 :(得分:0)

下面的查询应该带来相同的结果。 这看起来像是一个家庭作业问题。

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