这是我的名为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
我想返回所有记录,但是对于那些SPLIT值不是“ N”的记录,我希望有一列具有相同SESSION_ID的所有记录的持续时间之和。因此,对于上述内容,我想要:
SUB_ID SESSION_ID TOTAL_DURATION
1111 2468D 175
1111 3333A 5
2222 1357C 900
2222 4444B 20
我是一名SQL新手,因此以下是我使用CASE进行的最初尝试,但显然是错误的。有人可以协助我进行此汇总吗?
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
答案 0 :(得分:0)
GROUP BY
很重要;检查以下位置的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>