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

(‘Paul’,1,5,3),
(‘Scott’,41,35,32),
(‘Dan’,12,17,3)

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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: