SQL Statement Issue 合并 4 个表以获得要显示的正确信息

SQL Statement Issue combining 4 tables to get the correct information to display

我无法弄清楚这一点。我正在使用 MS SQL 2008 并尝试将未计费 table 和计费 table 的总技术时间相加并将它们组合在一起。如果计费报告无效,我还需要根据第三次 table 的报告 header 排除计费时间的行。然后我需要从第 4 个 table 中获取技术名称。 unbilled table 是SCQReportLabors,它列出了所有的劳务记录。 SCReportLabors table 列出所有计费人工记录。 SCReports 是计费报告 header,我需要确定 VoidID 列是否为空。 ShAgents table 持有技术名称。以下是我目前拥有的,我知道它不起作用,但这是我到目前为止所拥有的。对于我的输出数据,我想要一个 TotalHours 列和一个 TechName 列。如果我最终得到的是计费总额、未计费总额和技术名称列,我也可以接受。我已经盯着这个看了一会儿,需要一些观点和建议。在此先感谢您的帮助。

SELECT a.TotalHours, c.PrefFullName AS TechName
    FROM (SELECT SUM(LaborHours)+SUM(OvertimeHours)+SUM(TravelHours) AS TotalHours, TechnicianID 
        FROM SCReportLabors
        LEFT OUTER JOIN SCReports d ON a.ReportID = d.ReportID
    WHERE d.VoidID IS NULL
    GROUP BY TechnicianID) a
    JOIN (SELECT SUM(LaborHours)+SUM(OvertimeHours)+SUM(TravelHours) AS TotalHours, TechnicianID
      FROM SCQReportLabors
      GROUP BY TechnicianID) b
ON a.TechnicianID = b.TechnicianID
    LEFT OUTER JOIN ShAgents c ON a.TechnicianID = c.AgentID
ORDER BY c.PrefFullName

我将两个主要查询设为 UNION 查询,还修改了 VOID 列的 JOIN。

SELECT SQ1.TotalHours, SHA.PrefFullName AS TechName
FROM
(
SELECT SUM(TOTALHOURS) AS TotalHours, TechnicianID
    (SELECT SUM(LaborHours)+SUM(OvertimeHours)+SUM(TravelHours) AS TotalHours, TechnicianID 
    FROM SCReportLabors L
    JOIN SCReports RPTS
    ON L.ReportID = RPTS.ReportID
    WHERE RPTS.VoidID IS NULL
    GROUP BY TechnicianID)
    UNION ALL
    (SELECT SUM(LaborHours)+SUM(OvertimeHours)+SUM(TravelHours) AS TotalHours, TechnicianID
     FROM SCQReportLabors
     GROUP BY TechnicianID
     )
) SQ
GROUP BY TechnicianID
JOIN ShAgents SHA
ON SQ.TechnicianID = SHA.AgentID
ORDER BY SHA.PrefFullName

此查询应捕获所有数据并处理空小时。

SELECT
    A.PrefFullName AS 'TechName',
    (ISNULL(B.TotalHours, 0) + ISNULL(C.TotalHours, 0)) AS 'Total Hours'
FROM
    ShAgents AS A
    LEFT OUTER JOIN
        (
            SELECT 
                (
                    SUM(ISNULL(LaborHours, 0)) + 
                    SUM(ISNULL(OvertimeHours, 0)) + 
                    SUM(ISNULL(TravelHours, 0))
                ) AS 'TotalHours', 
                TechnicianID 
            FROM 
                SCReportLabors AS tA
                LEFT OUTER JOIN SCReports AS tB
                    ON tA.ReportID = tB.ReportID
            WHERE 
                tB.VoidID IS NULL
            GROUP BY 
                TechnicianID
        ) AS B
        ON A.AgentID = B.TechnicianID
    LEFT OUTER JOIN
        (
            SELECT 
                (
                    SUM(ISNULL(LaborHours, 0)) + 
                    SUM(ISNULL(OvertimeHours, 0)) + 
                    SUM(ISNULL(TravelHours, 0))
                ) AS 'TotalHours', 
                TechnicianID
            FROM 
                SCQReportLabors
            GROUP BY 
                TechnicianID
        ) AS C
        ON A.AgentID = C.TechnicianID
ORDER BY 
    A.PrefFullName