Postgres:获取哪一部分是一组中的记录

时间:2017-04-24 15:40:12

标签: sql postgresql

我试图获取或计算集合中每个记录的信息(分期付款和部分价值),我在下面用一个例子解释:

| pay        |  date       | value |
|:-----------|------------:|:-----:|
| 910006603  | 2017-04-19  | 30    |
| 910006603  | 2017-04-21  | 30    |
| 910006603  | 2017-04-23  | 30    |
| 910006603  | 2017-04-25  | 30    |  
| 910006604  | 2017-04-14  | 45    | 
| 910006604  | 2017-04-18  | 45    |

有了这些信息,我必须添加另外两列,指出它的分期付款和部分价值,以便结果:

| pay        |  date       | value | insta | partial|
|:-----------|------------:|:-----:|:-----:|:------:|
| 910006603  | 2017-04-19  | 30    | 1     | 30     |
| 910006603  | 2017-04-21  | 30    | 2     | 60     |
| 910006603  | 2017-04-23  | 30    | 3     | 90     |
| 910006603  | 2017-04-25  | 30    | 4     | 120    |

| 910006604  | 2017-04-14  | 45    | 1     | 45     | 
| 910006604  | 2017-04-18  | 45    | 2     | 90     |

我希望能够明确表示,谢谢。

2 个答案:

答案 0 :(得分:5)

您可以使用ROW_NUMBER()和SUM()window functions来获取它。

create table payments(pay int, dt date, value int);
insert into payments values
(910006603, '2017-04-19', 30),
(910006603, '2017-04-21', 30),
(910006603, '2017-04-23', 30),
(910006603, '2017-04-25', 30),
(910006604, '2017-04-14', 45),
(910006604, '2017-04-18', 45);
select pay, 
       dt as date, 
       value, 
       row_number() over (partition by pay order by dt) as insta,
       sum(value) over (partition by pay order by dt) as partial
from   payments;
      pay | date       | value | insta | partial
--------: | :--------- | ----: | ----: | ------:
910006603 | 2017-04-19 |    30 |     1 |      30
910006603 | 2017-04-21 |    30 |     2 |      60
910006603 | 2017-04-23 |    30 |     3 |      90
910006603 | 2017-04-25 |    30 |     4 |     120
910006604 | 2017-04-14 |    45 |     1 |      45
910006604 | 2017-04-18 |    45 |     2 |      90

dbfiddle here

答案 1 :(得分:0)

尝试此操作,如有任何疑问,请与我联系。

select pay, date, value,
       (select sum(value) from t t2 where t2.pay = t.pay and t2.date <= t.date) as partial,
       (select count(*) from t t3 where t3.pay = t.pay and t3.date <= t.date) as insta
from table t;