列和行之间的列表差异之和

时间:2018-12-11 01:31:40

标签: sql oracle

我正在尝试根据下表中SELL_ID的分组来获取行之间的差异,

表1-(表格式由GitHub表示)

 -H '"Authorization:' Bearer '${JWT}"'

我试图得到如下结果,

表2-

+---------+---------+----------+----------+------------------+---------+
| seq_ID  | REQ_ID  | CALL_ID  | SELL_ID  |     REGION       |  COUNT  |
+---------+---------+----------+----------+------------------+---------+
|    1    |    123  | C001     | S1       | AGL              |  510563 |
|    2    |    123  | C001     | S1       | USL              |  122967 |
|    3    |    123  | C001     | S1       | VALIC            |  614106 |
|    4    |    123  | C001     | S2       | Inforce          | 1247636 |
|    5    |    123  | C001     | S2       | NB               |       0 |
|    6    |    123  | C001     | S3       | Seriatim Summary | 1247636 |
+---------+---------+----------+----------+------------------+---------+

S1_vs_S2是+---------+---------+----------+----------+-------+ | seq_ID | REQ_ID | CALL_ID | Summary | COUNT | +---------+---------+----------+----------+-------+ | 1 | 123 | C001 | S1_vs_S2 | 0 | | 2 | 123 | C001 | S2_vs_S3 | 0 | | 3 | 123 | C001 | S3_vs_s1 | 0 | +---------+---------+----------+----------+-------+ (sum(count) from table1 where sell_id='S1')之间的差异

下面是我正在使用的代码,但无法获取结果,

(sum(count) from table1 where sell_id='S2')

2 个答案:

答案 0 :(得分:0)

这是您想要的吗?

select req_id, call_id, sell_id,
       lead(sell_id) over (partition by req_id, call_id order by seq_id) as next_sell_id,
       (cnt -
        lead(cnt) over (partition by req_id, call_id order by seq_id)
       ) as diff
from (select req_id, call_id, sell_id, sum(count) as cnt, min(seq_id) as seq_id
      from t
      group by req_id, call_id, sell_id
     ) t

答案 1 :(得分:0)

第一组数据在sell_id, req_id, call_id上。这是我代码中的子查询t。然后自我正确加入这个结果并显示出不同之处。唯一的问题是仔细构造join条件:

demo with your sample data

with t as (
  select sell_id sid, req_id, call_id, sum(cnt) cnt
    from table1 
    group by sell_id, req_id, call_id )
select case t1.sid when 'S1' then 1 when 'S2' then 2 when 'S3' then 3 end id, 
       t1.req_id, t1.call_id, t1.sid||'_vs_'||t2.sid call_id, t1.cnt - t2.cnt diff
  from t t1 
  join t t2 on t1.req_id = t2.req_id 
           and t1.call_id = t2.call_id 
           and (t1.sid, t2.sid) in (('S1', 'S2'), ('S2', 'S3'), ('S3', 'S1'))
  order by id

BTW count是Oracle保留字,在命名列等时请避免使用此类名称。