SELECT语句别名上的对象名称错误无效

时间:2016-09-22 13:13:22

标签: sql sql-server

我编写了一个SQL查询,它为两个嵌套的SELECT语句中的每一个分配一个别名,并尝试连接这些别名。

我的SQL查询如下:

SELECT EmpID,
       (SELECT EmpID
              ,Count(*) * 8 AS [FullDayHours]
        FROM [database].[dbo].[tblLogTimes] 
        WHERE ActivityID = 43 
        AND WorkDate BETWEEN '2015-12-31 00:00:00.000' AND '2016-09-30 00:00:00.000'
        GROUP BY EmpID) AS [Rec1]
      ,(SELECT EmpID
              ,(Count(*) * 4) AS [HalfDayHours] 
        FROM [database].[dbo].[tblLogTimes] 
        WHERE ActivityID = 44 
        AND WorkDate BETWEEN '2015-12-31 00:00:00.000' AND '2016-09-30 00:00:00.000'
        GROUP BY EmpID) AS [Rec2]
FROM [database].[dbo].[tblLogTimes] E
INNER JOIN [Rec1] ON E.EmpID = [Rec1].EmpID
INNER JOIN [Rec2] ON E.EmpID = [Rec2].EmpID

在尝试执行查询时,我遇到了错误:无效的对象名称' Rec1'。

我已经尝试了查询组件子语句的各种安排和配置,但无济于事。

非常欢迎见解,建议。 谢谢你的期待。

1 个答案:

答案 0 :(得分:3)

我相信这就是你将子查询移到join之后的目的:

SELECT EmpID, FullDayHours, HalfDayHours
FROM [StaffSuite].[dbo].[tblLogTimes] E
INNER JOIN (SELECT EmpID
              ,Count(*) * 8 AS [FullDayHours]
        FROM [StaffSuite].[dbo].[tblLogTimes] 
        WHERE ActivityID = 43 
        AND WorkDate BETWEEN '2015-12-31 00:00:00.000' AND '2016-09-30 00:00:00.000'
        GROUP BY EmpID) AS [Rec1] ON E.EmpID = [Rec1].EmpID
INNER JOIN (SELECT EmpID
              ,(Count(*) * 4) AS [HalfDayHours] 
        FROM [StaffSuite].[dbo].[tblLogTimes] 
        WHERE ActivityID = 44 
        AND WorkDate BETWEEN '2015-12-31 00:00:00.000' AND '2016-09-30 00:00:00.000'
        GROUP BY EmpID) AS [Rec2] ON E.EmpID = [Rec2].EmpID

但是,您可以使用conditional aggregation进一步简化它:

SELECT EmpID, FullDayHours, HalfDayHours
FROM [StaffSuite].[dbo].[tblLogTimes] E
INNER JOIN (SELECT EmpID
              ,Count(case when activityid = 43 then 1 end) * 8 AS [FullDayHours]
              ,Count(case when activityid = 44 then 1 end) * 4 AS [HalfDayHours]
        FROM [StaffSuite].[dbo].[tblLogTimes] 
        WHERE ActivityID IN (43,44)
        AND WorkDate BETWEEN '2015-12-31 00:00:00.000' AND '2016-09-30 00:00:00.000'
        GROUP BY EmpID) AS [Rec1] ON E.EmpID = [Rec1].EmpID