问题描述
这是一个示例表CALLRECORD:
+--------+------------+
|callid | rating |
|1 | |
|2 | 5 |
|3 | |
|4 | 1 |
|5 | |
+--------+------------+
输出呼叫总数,已评级呼叫数,平均评级和未评级呼叫数没有问题:
select count(*) as total from callrecord;
select count(*) as rated,avg(rating) as average_rating from callrecord where rating is not null;
select count(*) as unrated from callrecord where rating is null;
+--------+
|total |
|5 |
+--------+
+--------+------------+
|rated |average |
|2 |3 |
+--------+------------+
+--------+
|unrated |
|3 |
+--------+
+--------+--------+------------+---------+
|total |rated |average |unrated |
|5 |2 |3 |3 |
+--------+--------+------------+---------|
db 提琴here
解决方法
大多数聚合函数都会忽略null
值,因此您想要的更简单,您可能会认为:
select
count(*) total,-- total number of rows
count(rating) as rated,-- count of non-null ratings
avg(rating) average,-- avg ignore `null`
count(*) - count(rating) unrated -- count of null ratings
from mytable
,
尝试在SUM聚合中使用CASE语句。下面的示例。
{
"api_key": "YOUR_API_KEY","@type": "searchPublicChat","username": "@username"
}