2016-04-19 119 views
3

我有SQL查詢得到6列的表從聚合函數where條件句

mytable: 
TotalNumberOfRecords 
TotalDurationOfCalls 
AvgdurationPer 
TotalCallednumbers 
TotalCallednumbers 
Ratiocalledtoallcalls 

這些列導致的聚集功能。但每個人都有不同的條件句子以便從表中選擇。

我的查詢是這樣的:

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 

現在,我的問題是,我怎麼能在一個查詢執行此查詢來獲取一個表?

+0

你使用MySQL,SQL Server 2008或SQL Server 2012中:您可以通過製作case表達參數的聚集功能做到這一點?你已經標記了所有三個。另外,我不清楚你在問什麼。 –

+0

基於大量的證據,我將MySQL標記更改爲sql。 –

回答

4

你想要條件聚合。

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 
+0

*平均(條件2然後投(時間爲int)其他0結束)作爲AvgdurationPer *的情況下,這項工作?我認爲它應該是* avg(當condition2然後投射(持續時間爲int)結束時)爲AvgdurationPer *,兩者都會產生差異結果。 –

+0

@AbdulRasheed。 。 。我一般同意你的看法,但OP在'AVG()'之前顯然具有NULL值替換。 –