如何在PostgreSQL中为每一行获取特定周期内的行数?

时间:2019-06-05 20:05:01

标签: sql postgresql cumulative-sum

我在PostgreSQL中有一张表,我想为每一行获取在每行日期之前30天(包括每时每刻的行事件)的时间段内的行数。示例:

Event.         Date

A.                 2019-02-13

B.                 2019-02-15

C.                 2019-03-17

D.                 2019-03-19

E.                 2019-04-22

F.                  2019-04-23

G.                 2019-04-30

预期输出:

Event.         Date.                 Events occurred in last month

A.                 2019-02-13.     1

B.                 2019-02-15.     2

C.                 2019-03-17.     1

D.                 2019-03-19.     2

E.                 2019-04-22.     1

F.                  2019-04-23.     2

G.                 2019-04-30.     3

例如,对于事件B,上个月有两个事件:B本身和A,因为它发生于2019年2月15日不到30天。对于事件G,有三个事件,因为从上个月(从2019-03-30开始),已经发生了三个事件(G本身,E和F)。

如何在PostgreSQL查询中实现这一点?

致谢

1 个答案:

答案 0 :(得分:1)

使用带有窗口子句的窗口函数:

<form>
<input type="text" name="text1" Placeholder="something"><br>
  <input type="text" name="dasnk2" Placeholder="something else"><br>
  <button id="login" style="display: block" type="button" value="Log In" name="Submit" onclick="onClickHandler()">Submit</button>
</form>

<script>
function validate (first, second, third, fourth){/* put the validation code here */};

function onClickHandler() {
      arg1 = document.getElementsByName("text1")[0].value;
      arg2 = "Isaac";
      arg3 = document.getElementsByName("dasnk2")[0].value;
      arg4 = "Tewst";
      validate(arg1, arg2, arg3, arg4)
    }
</script>
相关问题