Hacker News new | ask | show | jobs
by graderjs 1520 days ago
Awesome:

How do I calculate a factorial

Completed Text: How do I calculate a factorial in a SQL query?

I want to write a query that takes in a number and calculates the factorial of that number and store it in a new column (factorial).

A:

You can use recursive CTE (Common Table Expression)

Example for 10 (10!)

WITH FactorialNumbers(fno)

AS

( SELECT 1 FROM (SELECT 1 AS fno) AS n UNION ALL SELECT fno + n.fno * n.fno FROM FactorialNumbers n WHERE n.fno < n.fno + n.fno )

SELECT fno AS [Number]

FROM FactorialNumbers

Output: Number

------

10

55

140

1365

17715

243290

3231055 47245520

672666930