I have a situation similar to the following...please excuse the lame example I used, but it outlines my needs...Declare @t1 table (name varchar(20) , Ind_Money int)Insert @t1Select 'Derek', 1 UNIONSelect 'Dave', 2 UnionSelect 'Dave', 3 UnionSelect 'Fred', 8 UnionSelect 'Fred', 4 Declare @t2 table (Group_name varchar(20) , Group_Money int)Insert @t2Select 'D Group', 50 UNIONSelect 'D Group', 20 UNIONSelect 'Other Group', 30 --1st query to show initial setupSelect Case when Name IN ('Derek', 'Dave') then 'D Group' else 'Other Group' End as Groups , Sum(Ind_Money) as CollectedMoneyFrom @t1 aGroup by Case when Name IN ('Derek', 'Dave') then 'D Group' else 'Other Group' End--2nd Query which adds the new summed 3rd column Select Case when Name IN ('Derek', 'Dave') then 'D Group' else 'Other Group' End as Groups , Sum(Ind_Money) as CollectedMoney , c.Total_Group_MoneyFrom @t1 aLeft outer join( Select Group_Name ,Sum(Group_Money) as Total_Group_Money From @t2 Group by Group_Name) c ON (Case when Name IN ('Derek', 'Dave') then 'D Group' else 'Other Group' End) = c.Group_NameGroup by Case when Name IN ('Derek', 'Dave') then 'D Group' else 'Other Group' End , c.Total_Group_MoneyWhat I am looking to avoid, for simplicity's sake, and also to avoid errors, it to be able to take the ON statement of the Left Join and call it by it's alias.IE:Instead of...ON (Case when Name IN ('Derek', 'Dave') then 'D Group' else 'Other Group' End) = c.Group_NameI want to be able to do...a.Groups = c.Group_Name
Does that make sense? Basically when does an alias become reference-able?Thanks!EDIT: I know this can be simplified by using a Temporary table and then joining to that, I was trying to avoid creating temps and getting it all in 1 go round. I believe a CTE would work in a similar fashion, but can it be accomplished otherwise?