2008-11-28

Product Aggregation in SQL Server

Ever wanted to write something like this in SQL Server:

SELECT PRODUCT(MYCOLUMN) FROM MYTABLE

Well, wish no more:

DECLARE @P FLOAT
SET @P = 1
SELECT @P = @P * MYCOLUMN FROM MYTABLE
SELECT @P

... provided you can use the query in a context that permits T-SQL that is (e.g. not in a view or a subquery).  Note that you can perform arbitrary aggregations using this technique (say, summing while respecting null contagion, concatenating strings... the mind boggles).