我有一个表格,我希望通过orig调用和term调用将其生成一行组。我会计算它有多少次传入和传出......这是表格
致电
|ID | originating call | terminating call | call type
| 1 | 123 | 123 | incoming
| 2 | 123 | 123 | outgoing
| 3 | 123 | 321 | incoming
| 4 | 123 | 321 | incoming
结果应该是
originating call | terminating call | incoming | outgoing
123 | 123 | 1 | 1
123 | 321 | 2 | 0
我已尝试将计数()作为传入计数()作为传出,但我不知道接下来应该做什么。我应该通过发起呼叫和终止呼叫对其进行分组吗?
答案 0 :(得分:3)
这称为条件聚合。您可以使用case
语句执行基本查询:
select originating, terminating,
sum(case when calltype = 'incoming' then 1 else 0 end) as incoming,
sum(case when calltype = 'outgoing' then 1 else 0 end) as outgoing,
from calltable ct
group by originating, terminating;
这适用于所有数据库。要使id
列在数据库之间有所不同。在SQL Server中,您可以这样做:
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 = 'outgoing' then 1 else 0 end) as outgoing,
from calltable ct
group by originating, terminating;
在MySQL中,你会得到id
:
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;
尽管case
在MySQL中工作正常,但这个版本使用的是在这种情况下很方便的简写。
答案 1 :(得分:0)
使用以下查询:
select originating, terminating,
sum(case when calltype ='incoming' then 1 else 0 end) as incoming,
sum(case when calltype ='outgoing' then 1 else 0 end) as outgoing,
from Table_Name
分组来源,终止;