Sql 分配计数至最大值

Sql 分配计数至最大值,sql,oracle,Sql,Oracle,我有以下两个表格: aux1: 个人计算机 A. 马克西 PC1 A1 1. PC1 A2 2. PC2 A1 1. PC2 A2 2. 好小问题。您可以对范围进行预处理,然后按范围合并,然后分发资源 例如,您可以执行以下操作: with aux (vk, pc) as ( select 'VK1', 'PC1' from dual union all select 'VK2', 'PC1' from dual union all select 'VK3', 'PC2'

我有以下两个表格:

aux1:

个人计算机 A. 马克西 PC1 A1 1. PC1 A2 2. PC2 A1 1. PC2 A2 2.
好小问题。您可以对范围进行预处理,然后按范围合并,然后分发资源

例如,您可以执行以下操作:

with aux (vk, pc) as (
    select 'VK1', 'PC1' from dual union all
    select 'VK2', 'PC1' from dual union all
    select 'VK3', 'PC2' from dual union all
    select 'VK4', 'PC2' from dual union all
    select 'VK5', 'PC1' from dual union all
    select 'VK6', 'PC1' from dual union all
    select 'VK7', 'PC2' from dual union all
    select 'VK8', 'PC2' from dual),
aux1 (pc, a, maxi) as (
    select 'PC1', 'A1', 1 from dual union all 
    select 'PC1', 'A2', 2 from dual union all 
    select 'PC2', 'A1', 1 from dual union all 
    select 'PC2', 'A2', 2 from dual),
s as (
  select a.*,
    coalesce(sum(maxi) over(partition by pc order by pc, a 
      rows between unbounded preceding and 1 preceding), 0) + 1 as first_maxi,
    sum(maxi) over(partition by pc order by pc, a) as last_maxi
  from aux1 a
),
x as (
  select a.*,
    row_number() over(order by vk) as rn
  from aux a
),
y as (
  select a.*,
    (select count(*) from x b where b.rn <= a.rn and b.pc = a.pc) as cnt
  from x a
)
select
  y.vk, y.pc, s.a,
  case when s.pc is not null then row_number() 
    over(partition by y.pc, s.a order by y.rn) end as order_a_pc,
  case when s.pc is not null then row_number() 
    over(partition by y.pc order by y.rn) end as order_pc
from y
left join s on s.pc = y.pc and y.cnt between s.first_maxi and s.last_maxi
order by y.rn
结果:

VK   PC   A       ORDER_A_PC  ORDER_PC
---  ---  ------  ----------  --------
VK1  PC1  A1               1         1
VK2  PC1  A2               1         2
VK3  PC2  A1               1         1
VK4  PC2  A2               1         2
VK5  PC1  A2               2         3
VK6  PC1  <null>      <null>    <null>
VK7  PC2  A2               2         3
VK8  PC2  <null>      <null>    <null>

请参阅上的运行示例。

伟大的解决方案!实际上,我认为其中一个CTE y是不必要的,因为这可以通过按pc顺序按vk对分区进行计数来实现,但总体解决方案是有效的。我现在要增加一点谜语。我将在另一个问题中发布它。