PostgreSQL笔记-聚合函数

本文介绍了一种使用SQL进行数据分组并添加行号的方法,通过row_number()函数实现行转列操作,并展示了如何根据不同条件调整行号的计算方式。适用于需要对大量数据进行快速分组和排序的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

row_number

-- 分组加编号 sql:
select 
	b.eps400,
	b.max_report_id,
   row_number() over (partition by b.eps400 order by b.max_report_id desc) nums
from (
     select eps400, transfer_num, max(report_id) max_report_id
     from t_report_num_seat_bind_approve a
     where a.approve_date is not null
     group by eps400, transfer_num
 ) b
 -- rs:
4000000003,397686,1
4000000003,396690,2
4000000005,285728,1
4000000005,285655,2
4000000005,9446,3
4000000040,231967,1
4000000055,64999,1

-- 分组编号,如果编号大于10,取一半,sql:
select bb.eps400, case when max(bb.nums) >= 10 then round(max(bb.nums) * 0.5) else max(bb.nums) end max_nums
from (
         select b.eps400,
                b.max_report_id,
                row_number() over (partition by b.eps400 order by b.max_report_id desc) nums
         from (
                  select eps400, transfer_num, max(report_id) max_report_id
                  from t_report_num_seat_bind_approve a
                  where a.approve_date is not null
                  group by eps400, transfer_num
              ) b
     ) bb
group by bb.eps400;
-- rs:
4000000003,2
4000000005,3
4000000040,1
4000000055,1

行转列···

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值