2013-06-19 59 views
15

我有一個表,如下所示:SQL:COUNT()基於列的值

CallID | CompanyID | OutcomeID 
---------------------------------- 
1234  | 3344  | 36 
1235  | 3344  | 36 
1236  | 3344  | 36 
1237  | 3344  | 37 
1238  | 3344  | 39 
1239  | 6677  | 37 
1240  | 6677  | 37 

我想創建一個計算的銷售成果的數量和所有其他的嘗試次數SQL腳本(什麼<> 36),是這樣的:

CompanyID | SalesCount | NonSalesCount 
------------------------------------------ 
3344  | 3   | 1 
6677  | 0   | 2 

有沒有辦法做一個COUNT(),其中包含像COUNT(呼叫標識WHERE OutcomeID = 36)的條件?

回答

53

您可以使用CASE表達式與骨料得到一個基於outcomeId值共計:

select companyId, 
    sum(case when outcomeid = 36 then 1 else 0 end) SalesCount, 
    sum(case when outcomeid <> 36 then 1 else 0 end) NonSalesCount 
from yourtable 
group by companyId; 

SQL Fiddle with Demo

+0

非常好,謝謝 – BrianKE

+0

@BrianKE:能否'outcomeid'永遠是NULL? – gbn

+0

謝謝你,謝謝你爵士!!!!! –

1

是。 Count不會計算NULL值,所以您可以這樣做:

select 
    COUNT('x') as Everything, 
    COUNT(case when OutcomeID = 36 then 'x' else NULL end) as Sales, 
    COUNT(case when OutcomeID <> 36 then 'x' else NULL end) as Other 
from 
    YourTable 

或者,您可以使用SUM,就像bluefeet所演示的那樣。

1
SELECT 
    companyId, SalesCount, TotalCount-SalesCount AS NonSalesCount 
FROM 
    (
    select 
     companyId, 
     COUNT(case when outcomeid = 36 then 1 else NULL end) SalesCount, 
     COUNT(*) AS TotalCount 
    from yourtable 
    group by companyId 
    ) X; 

使用這種相互排斥的圖案與COUNT(*)

  • 避免評估第二條件COUNT
  • 的(非常小)開銷給出正確的值,如果outcomeid可以是NULL

使用@ bluefeet的SQLFiddle添加空值

3

事情是這樣的:

SELECT companyId, 
    COUNT(CASE WHEN outcomeid = 36 THEN 1 END) SalesCount, 
    COUNT(CASE WHEN outcomeid <> 36 THEN 1 END) NonSalesCount 
FROM 
    yourtable 
GROUP BY 
    companyId 

應該努力 - COUNT()只計算不爲空值。