The Furious Bear The Furious Bear - 2 months ago 12
SQL Question

Invalid object name error on SELECT statement alias

I've written a SQL query which assigns an alias to each of two nested SELECT statements and attempts to join on these aliases.

My SQL query is as follows:

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


On attempted execution of the query, I'm experiencing an error: Invalid object name 'Rec1'.

I've tried various arrangements and configurations of the query component substatements but to no avail.

Insights, advice would be very welcome.
Thanks for looking.

Answer

I believe this is what you're after instead moving the subqueries to the 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

However you could use conditional aggregation to simplify it further:

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
Comments