我有 SQL 查询从
中给出 6 列的表mytable:
TotalNumberOfRecords
TotalDurationOfCalls
AvgdurationPer
TotalCallednumbers
TotalCallednumbers
Ratiocalledtoallcalls
这些列是聚合函数的结果。但每个人都有不同的 where 条件语句以便从表中选择。
我的查询是这样的:
select ID,
count(*) as TotalNumberOfRecords,
sum (isnull(cast(duration as int),0)) {where condition1} as TotalDurationOfCalls ,
AVG(isnull(cast(duration as int),0)){where condition2} as AvgdurationPer,
count(distinct IDS) {where condition3} as TotalCallednumbers ,
count(distinct CGI) {where condition4} as TotalOfLocations,
cast(count(distinct IDS) as float)/cast(count(*) as float) {where condition5} as Ratiocalledtoallcalls
from Mytable
group by ID
现在,我的问题是,如何在一个查询中执行此查询以获取一张表?
最佳答案
您需要条件聚合。为此,您可以将 case
表达式作为聚合函数的参数:
select ID, count(*) as TotalNumberOfRecords,
sum(case when condition1 then cast(duration as int) else 0 end) as TotalDurationOfCalls ,
avg(case when condition2 then cast(duration as int) else 0 end) as AvgdurationPer,
count(distinct case when condition3 then IDS end) as TotalCallednumbers,
count(distinct case when condition4 then CGI end) as TotalOfLocations,
cast(distinct count(case when condition5 then IDS end) as float)/cast(count(*) as float) as Ratiocalledtoallcalls
from Mytable
group by ID
关于sql - 不同where条件句的聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36716605/