创建一个计数,然后根据其他2列对列求和

时间:2020-10-09 00:39:32

标签: sql sql-server

我有一张名为call_logs sqlfidle的表:http://www.sqlfiddle.com/#!18/fce856

var new = await Person.create({ name: 'Axl Rose' });
//this would make new return

new['id']; // the id of the new created document.

我想要一个名为 Date call_time(slot) call_duration 2011-10-01 60 30 2011-10-01 60 15 2015-10-01 180 30 2005-10-05 30 45 2020-02-03 90 30 2020-05-03 15 15 2020-07-03 30 15 2005-02-26 30 15 2011-10-01 60 30 2010-10-01 60 30 2007-02-03 90 30 2018-05-31 90 30 2002-09-31 90 30 2009-11-31 90 30 的新表,该表显示发生了count_duration为60、90、15、120的x的call_duration

鉴于通话时间为60分钟,通话时间为30分钟,因此只有3个通话时间

输出表将如下所示:

call_time

我尝试使用此查询,但是恐怕我必须输入每个排列,但我不确定它现在是最好的选择

Date           call_time(slot)  call_duration      Count duration
2011-10-01         60                 30              3
2007-02-03         90                 30              2
2005-02-26         30                 15              2
2015-10-01        180                 30              1
2005-10-05         30                 45              1
2020-02-03         90                 30              5
2020-05-03         15                 15              1

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您只想要group by吗?

select date, call_time, call_duration, count(*)
from table1
group by date, call_time, call_duration
order by date, count(*) desc;

这会将计数放在单独的行而不是单独的列中-实际上,这就是您的结果。

答案 1 :(得分:0)

听起来您可能正在寻找GROUP BY日期和call_time以及交叉表或通过call_duration透视表列。通话时间是整数吗?像这样

select [date], call_time,
       sum(case when call_duration = 15 then 1 else 0) as duration_15
      ,sum(case when call_duration = 30 then 1 else 0) as duration_30
      ,sum(case when call_duration = 45 then 1 else 0) as duration_45
      ,sum(case when call_duration = 60 then 1 else 0) as duration_60
      ,sum(case when call_duration = 90 then 1 else 0) as duration_90
      ,sum(case when call_duration = 180 then 1 else 0) as duration_180
      ,sum(case when call_duration > 180 then 1 else 0) as duration_plus
from Table1
group by [date], call_time