[英]Find out the total call duration happened between 2 people
I want to find out the call duration between 2 persons through SQL. 我想通过SQL找出2个人之间的通话时间。 Say "Joe" calling "Mak" and spoke 5 minutes and "Mak" calling "Joe" for 15 minutes then total duration must be 20 minutes.
假设“乔”称呼“ Mak”并讲话5分钟,而“马克”称呼“ Joe” 15分钟,则总持续时间必须为20分钟。
I tried something with self join but getting duplicates for such calls. 我尝试使用自加入进行某些操作,但此类调用得到了重复。
SELECT t1.cal1, t2.cal2,sum(t1.dur) as Total
from tele t1
INNER JOIN tele t2
ON (t1.cal1 = t2.cal1 AND t1.cal2 = t2.cal2)
GROUP BY T1.CAL1, T2.CAL2;
cal1 cal2 duration (in Mins)
A B 5
A B 10
B A 10
B A 25
A D 1
D C 2
B C 4
C B 9
C B 7
C A 2
D C 5
D B 10
The simpler way is to use CASE so you get the unique combinations of col1 and col2 and then group by each combination: 比较简单的方法是使用CASE,以便获得col1和col2的唯一组合,然后按每种组合分组:
SELECT
case when cal1 < cal2 then cal1 else cal2 end col1,
case when cal1 < cal2 then cal2 else cal1 end col2,
SUM(duration) duration
FROM tele
GROUP BY col1, col2
See the demo . 参见演示 。
Results: 结果:
> col1 | col2 | duration
> :--- | :--- | -------:
> A | B | 50
> A | C | 2
> A | D | 1
> B | C | 20
> B | D | 10
> C | D | 7
In case you use SQLServer, you need this: 如果您使用SQLServer,则需要:
SELECT
case when cal1 < cal2 then cal1 else cal2 end col1,
case when cal1 < cal2 then cal2 else cal1 end col2,
SUM(duration) duration
FROM tele
GROUP BY
case when cal1 < cal2 then cal1 else cal2 end,
case when cal1 < cal2 then cal2 else cal1 end
or replace the CASE statements with 或将CASE语句替换为
You will have to dynamically set your columns in a subquery and group the results of it again to achieve your desired outcome: 您将必须在子查询中动态设置列,然后再次将其结果分组以实现所需的结果:
SELECT
col1, col2, SUM(duration)
FROM
(
SELECT
IF(cal1 < cal2, cal1, cal2) AS col1,
IF(cal1 < cal2, cal2, cal1) AS col2,
SUM(duration) AS duration
FROM
tel
GROUP BY
cal1,
cal2
) AS m
GROUP BY
col1,
col2
If a call A to B is equivalent to B to A, then it would probably help if you create a combined column consisting of both parties names - eg AB - with the order of the names in the combination determined by the sort order of the strings. 如果A到B的调用等效于B到A的调用,那么如果您创建一个由双方名称组成的组合列(例如AB),名称的顺序由字符串的排序顺序决定,则可能会有所帮助。
So for example, CASE WHEN A < B THEN A + B ELSE B + A END AS party_names
. 例如,
CASE WHEN A < B THEN A + B ELSE B + A END AS party_names
。
This will ensure both calls from A to B, and calls from B to A, result in a party_names
of AB. 这将确保从A到B的呼叫以及从B到A的呼叫都导致AB的
party_names
。
You can then GROUP BY and SELECT that column, and SUM(duration). 然后,您可以GROUP BY并选择该列以及SUM(duration)。
Most databases support least()
and greatest()
: 大多数数据库都支持
least()
和greatest()
:
select least(t.cal1, t2.cal2), greatest(t.cal1, t2.cal2),
sum(t1.dur) as Total
from tele t1
group by least(t.cal1, t2.cal2), greatest(t.cal1, t2.cal2);
For databases that do not, you can use a case
expression instead. 对于没有的数据库,可以改用
case
表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.