Skip to content
Advertisement

Column containing the product of elements in a second column, sorted by group

I have the following SQL script,

, which yields,

I wish to create a column, Product, that contains the product of Numbers on each date within the same BM group:

To clarify, for BM =’AA’ the product should be 1*2*3*4*5=120.

Thank you in advance! Best regards,

Advertisement

Answer

There isn’t a built-in product function; but you could use the exp/ln technique from this question, and adapt it to use an analytic sum:

DATE1 BM NUMBER1 PRODUCT
12-08-2021 AA 2 120
11-08-2021 AA 1 120
13-08-2021 AA 3 120
14-08-2021 AA 4 120
15-08-2021 AA 5 120
12-08-2021 BB 13 524160
11-08-2021 BB 12 524160
13-08-2021 BB 14 524160
15-08-2021 BB 16 524160
14-08-2021 BB 15 524160
11-08-2021 CC 22 7893600
12-08-2021 CC 23 7893600
14-08-2021 CC 25 7893600
13-08-2021 CC 24 7893600
15-08-2021 CC 26 7893600

db<>fiddle showing some of the intermediate steps.

The column names in your example are illegal so I assume you just changed those for posting; so I’ve modified them slightly to make them valid.

Note that if your number can be zero then you may need to exclude that to prevent it erroring; if you have negative values you’ll need to handle those differently too; and you might want to adjust the round() precision depending on your real data too.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement