I have two variables, one is called PaidThisMonth
, and the other is called OwedPast
. They are both results of some subqueries in SQL. How can I select the smaller of the two and return it as a value titled PaidForPast
?
The MIN
function works on columns, not variables.
Use a CASE statement.
Example B in this page should be close to what you're trying to do:
http://msdn.microsoft.com/en-us/library/ms181765.aspx
Here's the code from the page:
Building on the brilliant logic / code from mathematix and scottyc, I submit:
Although the jump from scottyc's MIN function to the MAX function should have been obvious to me, it wasn't, so I've solved for it and included it here: SELECT @a + ( ABS(@b-@a) + (@b-@a) ) / 2. The randomly generated numbers, while not proof, should at least convince skeptics that both formulae are correct.
The solutions using CASE, IIF, and UDF are adequate, but impractical when extending the problem to the general case using more than 2 comparison values. The generalized solution in SQL Server 2008+ utilizes a strange application of the VALUES clause:
Credit due to this website: http://sqlblog.com/blogs/jamie_thomson/archive/2012/01/20/use-values-clause-to-get-the-maximum-value-from-some-columns-sql-server-t-sql.aspx
For MySQL or PostgreSQL, a better way is to use the LEAST and GREATEST functions.
Both are described here: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html