Suppose I have a table: ACCOUNT
It has columns: ID, NAME, BALANCE
I want to determine if the SUM of balances of people who has balance more than $ 2,000 is greater than $ 50,000. It means I want to select a logical value. Because I don’t want to get specific sum, I only need comparison result. I want to be able to write something like:
SELECT SUM(BALANCE) > 50000
FROM ACCOUNT
WHERE BALANCE > 2000
Sql Server says it is syntax error. So I have to do:
SELECT SUM(BALANCE)
FROM ACCOUNT
WHERE BALANCE > 2000
Then compare the result to 50000. But taking sum of all the items after reaching 50000 is redundant since I only compare it to 50000.
So how can I write this query in a way to stop after reaching comparison value and give me the logical result?
This question was asked in 2011. In versions prior to 2012 there isn’t really a clean way of doing this and getting SQL Server to short circuit the scan as soon as the total is reached.
You could use a recursive CTE to add up the balances instead. The exit condition for this could be once the balance running total exceeds 50,000. Dependant on table cardinality and indexes this could be either more or less efficient.
You could also have a custom CLR aggregate that terminated processing by throwing an error if 50,000 was reached but quite a horrible solution!
For versions since 2012 see my answer here