很难解释,所以我会表现出来。这是我的示例数据:
CallRecords表:
CallerID CallLength Date
-------- ---------- ----
1000 200 2016-03-28
1001 300 2016-03-28
1000 450 2016-03-28
1002 600 2016-03-28
1002 610 2016-03-28
1001 340 2016-03-28
1000 400 2016-03-28
1001 444 2016-03-28
1002 100 2016-03-28
1000 280 2016-03-28
1002 670 2016-03-28
1000 200 2016-03-28
1001 300 2016-03-28
1001 450 2016-03-28
1000 600 2016-03-28
1002 610 2016-03-28
1000 340 2016-03-29
1000 400 2016-03-29
1002 444 2016-03-29
1000 140 2016-03-29
1001 280 2016-03-29
1001 670 2016-03-29
1002 400 2016-03-29
1002 444 2016-03-29
1001 140 2016-03-29
1001 280 2016-03-29
1000 670 2016-03-29
我想要显示为查询的输出:
CallerID #Calls<3Min Duration #Calls3-5Min Duration #Calls>5Min Duration
-------- ----------- -------- ----------- -------- ----------- --------
1000 1 140 3 680 6 2860
1001 1 140 4 1160 4 1904
1002 1 100 0 0 7 3778
我尝试过使用多个select语句,这需要很长时间(我的数据库显然要大得多)并且相当复杂。有没有简单的方法来构建查询?
感谢。
答案 0 :(得分:3)
执行GROUP BY
,并使用case
表达式执行条件count
/ sum
:
select CallerID,
count(case when CallLength < 180 then 1 end) as "#Calls<3Min",
sum(case when CallLength < 180 then CallLength else 0 end) as "Duration 3min's",
...
from tablename
group by CallerID