我有一个类似于下面的示例的表格,日期,num,借记,信用和余额(借记值 0-信用值),所以我想在使用记录中选择记录相同的数字和平衡和等于0,然后确定这些记录。
我正在尝试创建一个函数,但是我只在有两个平等记录的情况下才完成。在此示例中,是NUM219900。在其他情况下,我不能。
我想在其他记录中做,这是**。
date num debit credit balance zero_balance
11/11/2016 219900 470,00 -470,00 Y
11/11/2016 219900 470,00 470,00 Y
01/11/2016 218295 163,00 163,00
30/11/2016 218295 162,00 162,00 **Y**
30/11/2016 218295 162,00 162,00 **Y**
30/11/2016 218295 162,00 -162,00 **Y**
30/11/2016 218295 162,00 -162,00 **Y**
30/11/2016 218295 162,00 162,00
25/10/2016 218102 935,46 935,46 **Y**
25/10/2016 218102 935,46 -935,46 **Y**
25/10/2016 218102 935,46 935,46
20/10/2016 217638 1.896,65 1.896,65 **Y**
20/10/2016 217638 1.896,65 -1.896,65 **Y**
20/10/2016 217638 1.896,65 1.896,65 **Y**
20/10/2016 217638 1.896,65 -1.896,65 **Y**
20/10/2016 217638 1.696,65 1.696,65
有人可以帮我吗?
我将调用您的表t
(在查询中使用您自己的名字)。另外,我根本不会使用balance
字段;它似乎是多余的(但是答案也可以使用该列)。
如果您有一个主键,则只需给出每个num
的积分并借方索引一个索引(下面的cd_idx
)。您可以使用该索引搜索对。
with d as (
select t r, row_number() over (partition by num, credit, debit order by date, id) cd_idx
from t
)
select (d1.r).*, (d2.r).id is not null zero_balance
from d d1
left join d d2 on (d1.r).id <> (d2.r).id
and (d1.r).num = (d2.r).num
and d1.cd_idx = d2.cd_idx
and ((d1.r).credit = (d2.r).debit or (d1.r).debit = (d2.r).credit)
order by (d1.r).id
请注意,cd_idx
由date, id
以升序顺序为同一num, credit, debit
生成。另请注意,我将整个行放入r
列中,但是如果您只想选择特定的列(这样我就可以轻松地选择使用(d1.r).*
的所有属性)。
如果您没有主键,则可以使用row_number()
临时生成一个,但是这样您不能保证您获得多个执行的结果。
with t as (select *, row_number() over () id from t),
d as (
select t r, row_number() over (partition by num, credit, debit order by date, id) cd_idx
from t
)
select (d1.r).*, (d2.r).id is not null zero_balance
from d d1
left join d d2 on (d1.r).id <> (d2.r).id
and (d1.r).num = (d2.r).num
and d1.cd_idx = d2.cd_idx
and ((d1.r).credit = (d2.r).debit or (d1.r).debit = (d2.r).credit)
order by (d1.r).id
rextester
使用窗口功能https://www.postgresql.org/docs/current/static/tutorial-window.html我认为这应该为您提供帮助。
select
date
,num
,debit
,credit
,sum(debit) over (partition by num) as sum_deb
,sum(credit) over (partition by num) as sum_cred
,case when
sum(debit) over (partition by num) = sum(credit) over (partition by num)
then 'Y' else 'N' end as zero_balance
from test_debt