You have some errors on the way you want to generate the query. You can't combine the assignment of variables with the return of results and you need to write a CASE for each column on your query (at least).However, I don't understand why would you want to count a value returned by a formula. Wouldn't you need to use SUM?Here's my interpretation from your query. I have nothing to test and I don't know what you expect from this. For better answers, please read the article linked in my signature.