Thursday, 24 October 2013

1.14 - Product Function In SQL

As some of you may be aware there is no PRODUCT function in SQL so we have to find a solution ourselves. I searched for a few hours and found various ways of doing it using LOG but that did not work fully as it did not take account of negative numbers. I eventually started thinking about using a recursive CTE, tried, failed and looked for an alternative, when I remembered that you could use a variable as a recursive solution and hey presto! It worked; details below:

DECLARE @a DECIMAL(37, 9) = 1.00; -- As 1 * x will always start us off
WITH    cte
          AS (
               SELECT
                    ROW_NUMBER() OVER ( ORDER BY (
                                                   SELECT
                                                        ( NULL )
                                                 ) ) [row]
                FROM
                    sys.tables
UNION ALL --Add random data for test
(SELECT -5 [Row])
UNION ALL --Add random data for test
(SELECT 20 [Row])
UNION ALL --Add random data for test
(SELECT 5.26566666 [Row])
UNION ALL --Add random data for test
(SELECT -3 [Row])
)

    SELECT
            @a = ( @a * [row] ) --Set recursion of the variable
        FROM
            cte


SELECT
CONVERT(VARCHAR, CONVERT(MONEY, @a), 1) --Select in a nice format

No comments:

Post a Comment