在一行中输出一个表记录的多个计数

Vod*_*nik 1 sql informix average count sql-null

这是一个示例表 CALLRECORD:

    +--------+------------+
    |callid  |   rating   |
    |1       |            |
    |2       |   5        |
    |3       |            |
    |4       |   1        |
    |5       |            |
    +--------+------------+
Run Code Online (Sandbox Code Playgroud)

输出总通话数、评级通话数、平均评级和未评级通话数没有问题:

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;
Run Code Online (Sandbox Code Playgroud)
    +--------+
    |total   |
    |5       |
    +--------+

    +--------+------------+
    |rated   |average     |
    |2       |3           |
    +--------+------------+

    +--------+
    |unrated |
    |3       |
    +--------+
Run Code Online (Sandbox Code Playgroud)

我正在寻找如何使用单个 SQL 请求将以上所有内容输出到一行:

    +--------+--------+------------+---------+
    |total   |rated   |average     |unrated  |
    |5       |2       |3           |3        |
    +--------+--------+------------+---------|
Run Code Online (Sandbox Code Playgroud)

db<>在这里摆弄

GMB*_*GMB 5

大多数聚合函数会忽略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
Run Code Online (Sandbox Code Playgroud)