子查询上的GROUP BY不返回任何结果

时间:2018-06-14 11:38:00

标签: sql sql-server

首先介绍一下我要做的事情:

时间是根据工作进行预订,工作被组织到工作组中,我正在尝试计算工作组级别记录的小时数。

问题是如何存储小时数,使用" 10,000英尺"如果有人知道这个系统。

对于每个Job + User + Day,有两行,一行显示预定时间,另一行显示'实际'小时;虽然如果用户没有确认他们的预定时间(大部分时间没有确定没有差异),那么实际小时数为NULL,预定时间是需要使用的小时数。

因此,最好的方法是将这两行组合在一起,当实际小时数为NULL时,请使用预定的小时数。

此完整查询中的子查询可以正常工作并显示正确的小时数。

当放置在较大的查询中时,它显示null结果;删除子查询中的GROUP BY并显示数据但不计算实际为NULL时计划的小时数。

我知道答案就在这个查询中,但是我和它一起四处走动。

任何让我从不同的方法考虑这个问题的建议都会受到欢迎。

SELECT
    g1.om_number AS "Job Group Number",
    (
        SELECT
            CASE
                WHEN SUM(tkte2.TimeEntries_Hours) IS NOT NULL
                THEN SUM(tkte2.TimeEntries_Hours)
                ELSE
                (
                    CASE
                        WHEN SUM(tkte2.TimeEntries_Scheduled_Hours) IS NOT NULL
                        THEN SUM(tkte2.TimeEntries_Scheduled_Hours)
                        ELSE 0
                    END
                )
            END
        FROM TenK.TimeEntries AS tkte2
        INNER JOIN TenK.Projects AS tkp2 ON tkp2.Projects_Id=tkte2.TimeEntries_Assignable_Id
        INNER JOIN om.Job AS j2 ON tkp2.Projects_Code=j2.om_number
        WHERE j2.om_jobGroup_id=g1.om_id
        GROUP BY tkte2.TimeEntries_Assignable_Id,tkte2.TimeEntries_User_Id,tkte2.TimeEntries_Date
    ) AS "Hours"
FROM om.jobGroup AS g1
INNER JOIN om.Project AS p1 ON g1.om_project_id=p1.om_id
WHERE (CONVERT(date, p1.om_creationDate) BETWEEN CONVERT(date,'2016-01-01 00:00:00') AND CONVERT(date,'2019-12-31 23:59:59'))
AND g1.om_number='TESTJOB-01'

1 个答案:

答案 0 :(得分:1)

我使用OUTER APPLY稍微优化了您的查询,并确保包含必要的组(能)字段。

查询更简单,更清晰。

顺便说一下,确保(j2.om_jobGroup_id = g1.om_id)匹配,否则它将返回空。

```

SELECT
    g1.om_number AS [Job Group Number]
    , COALESCE(H.TimeEntries_Hours_SUM, H.TimeEntries_Scheduled_Hours_SUM) AS Hours
FROM om.jobGroup AS g1
INNER JOIN om.Project AS p1 ON g1.om_project_id=p1.om_id
OUTER APPLY
(
    SELECT tkte2.TimeEntries_Assignable_Id
        , tkte2.TimeEntries_User_Id
        , tkte2.TimeEntries_Date
        , SUM(tkte2.TimeEntries_Hours) AS TimeEntries_Hours_SUM
        , SUM(tkte2.TimeEntries_Scheduled_Hours) AS TimeEntries_Scheduled_Hours_SUM
    FROM TenK.TimeEntries AS tkte2
    INNER JOIN TenK.Projects AS tkp2 ON tkp2.Projects_Id = tkte2.TimeEntries_Assignable_Id
    INNER JOIN om.Job AS j2 ON tkp2.Projects_Code=j2.om_number
    WHERE (j2.om_jobGroup_id = g1.om_id)
    GROUP BY tkte2.TimeEntries_Assignable_Id, tkte2.TimeEntries_User_Id, tkte2.TimeEntries_Date
) H
WHERE (CONVERT(date, p1.om_creationDate) BETWEEN CONVERT(date,'2016-01-01 00:00:00') AND CONVERT(date,'2019-12-31 23:59:59'))
    AND g1.om_number='TESTJOB-01';

```