sql - 不同where条件句的聚合函数

标签 sql sql-server sql-server-2008 sql-server-2012

我有 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/

相关文章:

sql - PostgreSQL:LEFT JOIN 不返回整个左表

sql - CTE-- 获取父级

sql-server - TSQL : Incrementing a column value based on another column's value (SQL Server)

sql - 在 SQL Server 中给定以下 XML,如何获取值?

sql - 存储过程返回的别名列 [SQL Server 2008]

mysql - 在另一个查询中使用表别名来遍历树

mysql - sql从一个表插入数据到另一个表

c# - 远程数据库良好实践

sql - 避免在查询中使用 "SELECT TOP 1"和 "ORDER BY"

sql - 使用带有 MAX() 的 GROUP BY 作为聚合与使用 ROW_NUMBER 进行分区相比,是否存在性能差异?