我正在尝试编写以下查询以按组获取行计数。
select
a.employee, a.cov_option,
count(a.cov_option) over (partition by a.cov_option order by a.employee) as row_num
from wilson.benefit a
inner join wilson.bncategory b
ON a.plan_type = b.plan_type and a.plan_option = b.plan_option
inner join wilson.bncovopt c
ON a.company = c.company and a.plan_code = c.plan_code and a.cov_option = c.coverage_opt
where
a.plan_type = 'HL' and
to_char(a.stop_date, 'yyyy-mm-dd') = '1700-01-01'
order by a.employee, a.cov_option
返回的结果集是:
employee | cov_option |row_num
-------------|--------------|--------------
429 | 1 | 1
429 | 3 | 2
429 | 3 | 2
1420 | 1 | 2
1420 | 3 | 4
1420 | 3 | 4
1537 | 2 | 2
1537 | 2 | 2
我试图返回的结果集是:
429 | 1 | 1
429 | 3 | 2
429 | 3 | 2
1420 | 1 | 1
1420 | 3 | 2
1420 | 3 | 2
1537 | 2 | 1
1537 | 2 | 1
答案 0 :(得分:0)
您似乎想要的是dense_rank()
而不是count()
。实际上,“计数”意味着简单地确定每组中有多少行,它不像我们作为儿童学习的那样“计数”(第一,第二,第三)。这种计数称为“排名”。
dense_rank() over (partition by a.employee order by a.cov_option) as row_num
应该做你需要的。
还有rank()
- 区别在于,如果首先绑定两行,则dense_rank()
第三行行获得排名2;简单rank()
它获得排名3(排名2被前两行“用完”)。