Aggregating fields within a record

If for example you want to find a max across several fields within a record one way of doing it is via a PIVOT operation, here is another (possibly more intuitive) option

what we are doing here is turning the columns we want to aggregate into rows and then aggregating by this new column

DECLARE @data TABLE (Name VARCHAR(10),field1 int, field2 int, field3 int)

insert into @data VALUES


SELECT Name,max(a) AS max_of_fields_1_to_3
FROM @data a
CROSS APPLY (VALUES (field1),(field2),(field3)) b(a)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: