โ Sum or Max of Multiple Columns
Configurable Joins makes it easy to use the aggregate SQL functions like SUM() or MAX(). However, these operate across rows - what you want the max or sum of several columns on the same row? ๐ฃโโ๏ธ
Sum
Using a table value constructor allows for summing up all non-null values from a set. Replace @valueX
with your whatever exports you desire.
(SELECT SUM(v)
FROM (
ย ย VALUES (@value1)
ย ย ย ย ,(@value2)
ย ย ) AS t(v))
Occasionally, you may encounter datatype errors when all values are NULL and have datatypes incompatible with SUM(). Adding the following extra โvalueโ should prevent this.,(cast(NULL AS INT)) /* Prevent datatype error */
Max
Similarly, a table value constructor can also return the maximum non-null value from a set:
(SELECT MAX(v)
FROM (
ย ย VALUES (@value1)
ย ย ย ย ,(@value2)
ย ย ) AS t(v))
However, thereโs an easier way as of SQL Server 2022: the GREATEST() function! It does essentially the same thing with less fuss.
GREATEST(@value1, @value2)
No Comments