具有滞后列的列

问题描述 投票:1回答:2

我有这个查询

SELECT CASE WHEN LAG(emp_id) OVER( ORDER BY NULL ) = emp_id THEN '-'
            ELSE  emp_id END "Employee ID",
       row_number() over (partition by emp_id order by emp_id) as "S/N",  
       family_mem_id   "MemID",
       CASE WHEN LAG(emp_id) OVER(ORDER BY NULL ) = emp_id THEN 0 
            ELSE (SUM(amount_paid) OVER(PARTITION BY emp_id)) END "Total amount"
FROM    Employee 
ORDER   BY emp_id;

它向我显示了这样的结果:Resultset

我想为两行之间的员工ID添加行号(第一列SN),例如,我想将其设置为null。对于员工ID-> S / N 2-> F904(SN应该为空)。我该怎么办?

oracle lag rownum
2个回答
0
投票

您可以使用外部查询如下创建SN列:

SELECT CASE WHEN "S/N" = 1 THEN '<1>' END AS SN, T.* FROM -- added this
(SELECT 
       CASE WHEN LAG(emp_id) OVER( ORDER BY NULL ) = emp_id THEN '-'
            ELSE  emp_id END "Employee ID",
       row_number() over (partition by emp_id order by emp_id) as "S/N",  
       family_mem_id   "MemID",
       CASE WHEN LAG(emp_id) OVER(ORDER BY NULL ) = emp_id THEN 0 
            ELSE (SUM(amount_paid) OVER(PARTITION BY emp_id)) END "Total amount"
FROM    Employee ) T
ORDER BY "Employee ID", "S/N"; -- Added this

请注意,我还更改了ORDER BY子句(将其移至外部查询)。

干杯!


0
投票

使用dense_rank()枚举行:

select case lag(emp_id) over( order by emp_id ) when emp_id then null 
            else '<'||dense_rank() over (order by emp_id)||'>'
       end sn,
       nullif(emp_id, lag(emp_id) over( order by emp_id )) empid,
       row_number() over (partition by emp_id order by emp_id) rn,  
       family_mem_id memid,
       case lag(emp_id) over(order by emp_id) when emp_id then null 
            else (sum(amount_paid) over(partition by emp_id)) 
       end total
  FROM  Employee order by emp_id;

[dbfiddle和示例输出:

SN   EMPID     RN MEMID      TOTAL
---- ----- ------ ----- ----------
<1>  101        1 F901         200
                2 F904  
<2>  102        1 F901         135
                2 F901  
<3>  103        1 F901         185
                2 F901  
                3 F901  
© www.soinside.com 2019 - 2024. All rights reserved.