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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.