我希望能够为每个 ID 获取负值和正值的数量。
示例 Fiddle
ID=1 有 2 笔正交易和 0 笔负交易。等等。
with trans_detail as
(
select 1 as trans_id, 100 as trans_amount from dual union all
select 1 as trans_id, 200 as trans_amount from dual union all
select 2 as trans_id, -100 as trans_amount from dual union all
select 2 as trans_id, -300 as trans_amount from dual union all
select 3 as trans_id, 400 as trans_amount from dual union all
select 3 as trans_id, -500 as trans_amount from dual
)
select trans_id,
count(*) over (partition by trans_id) as pos_count,
count(*) over (partition by trans_id) as neg_count
from trans_detail
where trans_amount > 0
UNION
select trans_id,
count(*) over (partition by trans_id) as pos_count,
count(*) over (partition by trans_id) as neg_count
from trans_detail
where trans_amount < 0;
期望结果:
ID POS_COUNT NEG_COUNT
---- ----------- -----------
1 2 0
2 0 2
3 1 1