我有这个表,根据call_type记录的持续时间为秒。现在我想显示呼叫类型的传入和传出以及它在一行中的持续时间。
致电
|ID | originating call | terminating call | call type | duration_seconds
| 1 | 123 | 123 | incoming | 60
| 2 | 123 | 123 | outgoing | 120
| 3 | 123 | 321 | incoming | 210
| 4 | 123 | 321 | incoming | 140
,结果将是
|ID | originating call | terminating call | incoming | duration | outgoing | duration
| 1 | 123 | 123 | 1 | 60 | 1 | 120
| 2 | 123 | 321 | 2 | 350 | 0 | 0
到目前为止,这是我的查询。
select @id := @id + 1 as id,
originating, terminating,
sum(calltype = 'incoming') as incoming,
sum(calltype = 'outgoing') as outgoing,
from calltable ct cross join
(select @id := 0) const
group by originating, terminating;
originating call | terminating call | incoming | outgoing
123 | 123 | 1 | 1
123 | 321 | 2 | 0
答案 0 :(得分:1)
只需添加另外两列基于calltype,就像您对传入和传出一样,除了不计算1
,使用duration_seconds
select row_number() over (order by (select NULL)) as id,
originating, terminating,
sum(case when calltype = 'incoming' then 1 else 0 end) as incoming,
sum(case when calltype = 'incoming' then duration_seconds else 0 end) as in_duration,
sum(case when calltype = 'outgoing' then 1 else 0 end) as outgoing,
sum(case when calltype = 'outgoing' then duration_seconds else 0 end) as out_duration
from calltable ct
group by originating, terminating;
根据您更新的问题,这是mysql。
select @id := @id + 1 as id,
originating, terminating,
sum(calltype = 'incoming') as incoming,
sum(if(calltype = 'incoming',duration_seconds,0)) as in_duration,
sum(calltype = 'outgoing') as outgoing,
sum(if(calltype = 'outgoing',duration_seconds,0)) as out_duration
from calltable ct cross join
(select @id := 0) const
group by originating, terminating;