I have a subquery ( LastActivityOn ) that I would like to use in three places: the SELECTed output clause, ORDER BY and WHERE.
SELECT TOP 175 (SELECT MAX(ActivityDate) FROM (VALUES (UserRegistration.CreatedOn), (UserRegistration.ActivatedOn), (UserRegistration.LastLoginOn), (UserRegistration.UpdatedOn), (UserProfile.LastPostedOn)) AS AllDates(ActivityDate)) LastActivityOn, UserRegistration.FirstName, UserRegistration.LastName, [15 more columns of various calculated distances, coalesces, etc...] FROM UserRegistration INNER JOIN UserProfile ON UserRegistration.Id = UserProfile.RegistrationId INNER JOIN ( SELECT PostalCode, GeoCenter, PrimaryCity, StateOrProvince FROM PostalCodes WHERE @OriginPostalCode IS NULL OR PostalCodes.GeoCenter.STDistance(@OriginPoint) < @WithinMeters ) AS ProximalPostalCodes ON ProximalPostalCodes.PostalCode = UserRegistration.PostalCode [7 more joins including full-text queries] WHERE LastActivityOn > @OldestUserToSearch AND [20 more lines of filtering logic] ORDER BY LOG(DATEDIFF(WEEK, LastActivityOn, @Today))/LOG(2), FullTextRelevance
Notice the three LastActivityOn events. Also note that the LastActivityOn subquery refers to two tables. I suppose because it depends on the join clause in the parent query, is this essentially a correlated subquery?
When I took a maximum of two dates using the User-Defined-Function function, I was able to use the resulting value in my WHERE and ORDER BY. Now I canβt.
It seems that I have several options ... I could wrap it all in another query, repeating the projection with only added activity. It seems that I can use "WITH" (CTE) in the same way.
But since I do not clearly understand the rules of when I can and cannot use the subquery the way I want, I could easily miss something. Any ideas?
Or maybe the SQL SERVER will be smart enough to perform calculations only once for each output line, and I should not worry about that?
EDIT: SQL Server 2008 Standard is currently in progress, but the upgrade will be fine at some point. In addition, RE: journal function - I work to combine with relevance as a weighted sum, so work is in progress. I either crop it with INT to use it as a ranking type, or add it to fit the linear setting.
CORRECTION: I was able to use the subquery alias in my ORDER BY, but not with any additional calculations or in the where clause. Thanks ypercube for pointing this out.