Skip to main content

โž• 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? ๐Ÿšฃโ€โ™€๏ธ

Example of trying and failing to use Maximum on multiple exports:

image.png

Solution:ย Table value constructors make it easy to apply aggregate functions across columns. Example use cases:

  • Select the latest of three or more dates from different bases
  • Select the minimum of three or more dates
  • Compute the average of multiple exports

This article lists two examples, but any aggregate function will work.

Max

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))

image.png

However, thereโ€™s an easier way: the GREATEST() function! It does essentially the same thing with less fuss.

GREATEST(@value1, @value2)

Sum

Easily sum 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 */