尝试加入两个调用临时表的选择查询

时间:2016-11-12 00:03:24

标签: sql join sql-server-2008-r2 temp-tables

我正在尝试构建一个相当复杂的查询,我一直陷入困境。我认为这是用随后的列追加我的表的最佳方法。我出于兼容性原因使用SQL Server 2008 R2与我需要访问的服务器。

这与我的相似:

SELECT
    FirstSet.PID
    ,FirstSet.PNAME
    ,FirstSet.PTYPE
    ,FirstSet.CONTACT_DATE
    ,FirstSet.P_Start_Time
    ,FirstSet.P_End_Time
    ,FirstSet.ShiftBlock
    ,SecondSet.NumEncCompleted
    ,SecondSet.NumEncScheduled
FROM
    (SELECT
         a.PID, a.PNAME, a.PTYPE,
         st.CONTACT_DATE,
         MIN(st.SLOT_BEGIN_TIME) AS 'P_Start_Time',
         MAX(st.SLOT_END_TIME) AS 'P_End_Time',
         CAST(DATEDIFF(MINUTE , MIN(st.SLOT_BEGIN_TIME) , MAX(st.SLOT_END_TIME)) AS NUMERIC(18 , 2)) / 60 AS 'HoursWorkedInDay',
         CASE 
            WHEN CAST(DATEDIFF(MINUTE , MIN(st.SLOT_BEGIN_TIME) , DATEADD(MINUTE, 30, MAX(st.SLOT_END_TIME))) AS NUMERIC(18 , 2)) / 60 BETWEEN 1 AND 5 
               THEN 1
            WHEN CAST(DATEDIFF(MINUTE , MIN(st.SLOT_BEGIN_TIME) , DATEADD(MINUTE, 30, MAX(st.SLOT_END_TIME))) AS NUMERIC(18 , 2)) / 60 BETWEEN 5 AND 10 
               THEN 2
         WHEN CAST(DATEDIFF(MINUTE , MIN(st.SLOT_BEGIN_TIME) , DATEADD(MINUTE , 30 , MAX(st.SLOT_END_TIME))) AS NUMERIC(18 , 2)) / 60 BETWEEN 10 AND     13 THEN 3
             ELSE NULL
        END AS 'ShiftBlock'
    FROM
        #SlotsTable st
    LEFT JOIN 
        #VisitsTable vt ON st.PID = vt.PID
    LEFT JOIN 
        #ARPB a ON st.CONTACT_DATE = a.SERVICE_DATE
            AND st.PID = a.PID
    WHERE
        st.SLOT_BEGIN_TIME >= @Report_Start_Date
        AND st.SLOT_BEGIN_TIME < @Report_End_Date
    GROUP BY
        st.CONTACT_DATE, a.PID, a.PNAME,
        a.PTYPE) AS FirstSet
INNER JOIN
    (SELECT
    a.PID
   ,a.PNAME
   ,st.CONTACT_DATE
   ,vt.NumEncCompleted
   ,vt.NumEncScheduled
FROM
    #SlotsTable st
    LEFT JOIN #VisitsTable vt
    ON st.PID = vt.PID
    LEFT JOIN #ARPB a
    ON st.CONTACT_DATE = a.SERVICE_DATE
    AND st.PID = a.PID
WHERE
    st.SLOT_BEGIN_TIME >= @Report_Start_Date
    AND st.SLOT_BEGIN_TIME < @Report_End_Date
GROUP BY
    a.PID
   ,a.PNAME
   ,st.CONTACT_DATE
   ,vt.NumEncCompleted
   ,vt.NumEncScheduled   
) 
AS SecondSet
ON FirstSet.PROV_ID = SecondSet.PROV_ID
ORDER FirstSet.PROV_ID

我认为这是我需要采取的方法,但是现在我遇到了格式错误。否则,当我尝试使用移位计算将NumEncCompleted或NumEncScheduled添加到Select查询中时,我最终返回每个CONTACT_DATE的多个结果,似乎将多个PID的值添加为单个PID结果。我在每个临时表之前都有以下内容:

IF OBJECT_ID ('tempdb'..'#TempTable') IS NOT NULL
DROP TABLE #TempTable

任何提示将不胜感激。

0 个答案:

没有答案