sql - Invalid object name error on SELECT statement alias -


i've written sql query assigns alias each of 2 nested select statements , attempts join on these aliases.

my sql query follows:

select empid,        (select empid               ,count(*) * 8 [fulldayhours]         [database].[dbo].[tbllogtimes]          activityid = 43          , workdate between '2015-12-31 00:00:00.000' , '2016-09-30 00:00:00.000'         group empid) [rec1]       ,(select empid               ,(count(*) * 4) [halfdayhours]          [database].[dbo].[tbllogtimes]          activityid = 44          , workdate between '2015-12-31 00:00:00.000' , '2016-09-30 00:00:00.000'         group empid) [rec2] [database].[dbo].[tbllogtimes] e inner join [rec1] on e.empid = [rec1].empid inner join [rec2] on e.empid = [rec2].empid 

on attempted execution of query, i'm experiencing error: invalid object name 'rec1'.

i've tried various arrangements , configurations of query component substatements no avail.

insights, advice welcome. looking.

i believe you're after instead moving subqueries join:

select empid, fulldayhours, halfdayhours [staffsuite].[dbo].[tbllogtimes] e inner join (select empid               ,count(*) * 8 [fulldayhours]         [staffsuite].[dbo].[tbllogtimes]          activityid = 43          , workdate between '2015-12-31 00:00:00.000' , '2016-09-30 00:00:00.000'         group empid) [rec1] on e.empid = [rec1].empid inner join (select empid               ,(count(*) * 4) [halfdayhours]          [staffsuite].[dbo].[tbllogtimes]          activityid = 44          , workdate between '2015-12-31 00:00:00.000' , '2016-09-30 00:00:00.000'         group empid) [rec2] on e.empid = [rec2].empid 

however use conditional aggregation simplify further:

select empid, fulldayhours, halfdayhours [staffsuite].[dbo].[tbllogtimes] e inner join (select empid               ,count(case when activityid = 43 1 end) * 8 [fulldayhours]               ,count(case when activityid = 44 1 end) * 4 [halfdayhours]         [staffsuite].[dbo].[tbllogtimes]          activityid in (43,44)         , workdate between '2015-12-31 00:00:00.000' , '2016-09-30 00:00:00.000'         group empid) [rec1] on e.empid = [rec1].empid 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -