我有一张表格如下:
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这样的条件(CallID WHERE OutcomeID = 36)?
答案 0 :(得分:61)
您可以对您的聚合使用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;
答案 1 :(得分: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()
只计算非空值。
答案 2 :(得分:2)
是。 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演示。
答案 3 :(得分:2)
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添加了NULL
答案 4 :(得分:0)
知道 COUNT()
和 SUM()
只计算非空值和以下规则:
true or null = true
false or null = null
为了摆弄,您可以采用 Taryn 的答案并以一种超级脏且容易出错的方式完全绕过 CASE
!
select companyId,
sum(outcomeid = 36 or null) SalesCount,
sum(outcomeid <> 36 or null) NonSalesCount
from yourtable
group by companyId;
忘记添加 or null
,您将计算所有内容!