简体   繁体   English

基于不同列中相似值的总和

[英]Sum based on similiar values in different column

This is my table called USAGE_TABLE: 这是我的名为USAGE_TABLE的表:

SUB_ID  SESSION_ID  SPLIT  DURATION
1111    2468D       S1     50
1111    2468D       S2     100
1111    3333A       N      5
1111    2468D       S3     25
2222    1357C       S1     200
2222    1357C       S2     300
2222    1357C       S3     400
2222    4444B       N      20

I want to return all records, but for those that have a SPLIT value other than 'N', I want to have a column with sum of the duration for all records with the same SESSION_ID. 我想返回所有记录,但是对于那些具有“ N”以外的SPLIT值的记录,我希望有一列具有相同SESSION_ID的所有记录的持续时间之和。 So for the above, I would want: 因此,对于以上内容,我希望:

SUB_ID  SESSION_ID  TOTAL_DURATION
1111    2468D       175
1111    3333A         5
2222    1357C       900
2222    4444B        20 

I am a SQL novice, so below was my initial attempt by using a CASE, but is clearly wrong. 我是一名SQL新手,因此以下是我使用CASE进行的最初尝试,但显然是错误的。 Can someone assist with how I could do this aggregation? 有人可以协助我进行此汇总吗?

SELECT SUB_ID,
SESSION_ID,
CASE
    WHEN SPLIT != ‘N’ THEN SUM(DURATION) FROM USAGE_TABLE GROUP BY SESSION_ID
    ELSE DURATION
END AS TOTAL_DURATION
FROM USAGE_TABLE

GROUP BY matters; GROUP BY事项; check the DECODE within: 检查以下范围内的DECODE

SQL> with usage_table (sub_id, session_id, split, duration) as
  2    (select 1111, '2468D', 'S1',  50 from dual union all
  3     select 1111, '2468D', 'S2', 100 from dual union all
  4     select 1111, '3333A', 'N',    5 from dual union all
  5     select 1111, '2468D', 'S3',  25 from dual union all
  6     --
  7     select 2222, '1357C', 'S1', 200 from dual union all
  8     select 2222, '1357C', 'S2', 300 from dual union all
  9     select 2222, '1357C', 'S3', 400 from dual union all
 10     select 2222, '1357C', 'N',   20 from dual
 11    )
 12  SELECT sub_id, session_id, sum(duration) total_duration
 13  from usage_table
 14  group by sub_id, session_id, decode(split, 'N', 1, 2)
 15  order by sub_id, session_id;

    SUB_ID SESSI TOTAL_DURATION
---------- ----- --------------
      1111 2468D            175
      1111 3333A              5
      2222 1357C             20
      2222 1357C            900

SQL>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM