使用Postgresql计算数学系列

时间:2017-07-12 16:48:49

标签: sql postgresql select

我需要在Postgresql select语句中计算一个数学系列,并将结果添加为名为“total_days”的列。公式为

enter image description here

变量 insts 来自SQL表本身。是否可以在不使用PL / SQL的情况下进行计算?

3 个答案:

答案 0 :(得分:2)

你的公式基本上是30 *(数字1..n之和)。

从1到n的数字总和公式为:n *(n + 1)/ 2。

所以SQL select语句是:

select 30*insts*(insts+1)/2 from YOUR_TABLE

答案 1 :(得分:2)

在这种情况下,您可以从总和中提取30,并使用封闭式表格解决方案<html> <head><title>HTML and JAVASCRIPT example</title> <script> function what() { if (document.ThisForm.Username.value == "Example Username" && document.ThisForm.Password.value == "Example Password") { document.location.href = "loginsuccess.html" } </script> </head> <body> <form name="ThisForm"> <table> <tr> <td>Username or CMSCE email:</td> <td><input type="text" size="70" name="Username" id="hi"></td> </tr> <tr> <td>Password:</td> <td><input type="password" size="70" name="Password" id="bye"></td> </tr> <tr> <td><input type="button" onClick="what()" value="Login" style="color: white; background-color: black"></td><td><input type="reset" value="Clear all"></td> </tr></table></form> </body> </html> Wikipedia

如果您有一个没有封闭表单的系列,您仍然可以在SQL中执行此操作:

30 * (1 + 2 + 3 + .... + insts) = 30 * insts * (insts + 1) / 2

答案 2 :(得分:0)

这就是你要找的东西吗?

create temp table vals ( val integer);
insert into vals (val) values (1), (2), (3);

select val, sum(x)
from (select val, generate_series(1,val)*30 as x from vals) as y
group by val;