We help IT Professionals succeed at work.

Can you reuse already determined calculations in select statements? e.g

dgloveruk
dgloveruk asked
on
If I have this valid select part of a statement to work out a distribution of events :

SELECT  
            SUM(CASE WHEN CreatedDate BETWEEN Dateadd(month, - 1, getdate()) AND getdate() THEN 1 ELSE 0 END) AS Period,             COUNT(LastClientCareCall.ContactId) AS NumberOfClients


I need to add a percentage calculation and my instinct is to append to the end something like ",100/NumberOfClients*Period as PercentageOfPeriod" but this is of course not possible.  I could obviously reuse all my formulas and make a very long winded "100/COUNT(LastClientCareCall.ContactId)*SUM(CASE WHEN CreatedDate BETWEEN Dateadd(month, - 1, getdate()) AND getdate() THEN 1 ELSE 0 END)" but wondered if there was a mechanism for using the output of the previously used alias's to achieve something more tidy?

Thanks in advance
Comment
Watch Question

SQL Server Data Dude
Most Valuable Expert 2013
Author of the Year 2015
Commented:
afaik nope, as the SELECT clause processes as a whole and not left-to-right where the left columns are retained in memory before the right ones are processed.  The main workaround would be to have your needed calculations in a subquery, and the ones that use them in a main query.   Something like..

SELECT a, b, the_count / the_sum as the_percent
FROM ( 
   SELECT a, b, COUNT(b) as the_count, SUM(b) as the_sum
   FROM some_table) one

Open in new window


I'm not quite understanding your calculations, so if you can give a data mockup maybe I'll be able to provide custom SQL to match.

Author

Commented:
Hi Jim,
That will be fine, I will nest the 1st query inside and then work with the alias names as you demonstrate.
Thank you!
Regards,
Jim HornSQL Server Data Dude
Most Valuable Expert 2013
Author of the Year 2015

Commented:
Thanks for the grade.  Good luck with your stuff.  -Jim