在一行中输出若干条 table 条记录

Output several counts of one table records in one row

这是一个例子table通话记录:

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

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

    +--------+--------+------------+---------+
    |total   |rated   |average     |unrated  |
    |5       |2       |3           |3        |
    +--------+--------+------------+---------|

db<>fiddle 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 语句一起使用。示例如下。

 Select 
        COUNT(*) AS 'Total', 
        SUM(CASE WHEN rating IS NULL THEN 0 ELSE 1 END) AS 'Rated',
        (SUM(CASE WHEN rating IS NULL THEN 0 ELSE rating END)/SUM(CASE WHEN rating IS NULL THEN 0 ELSE 1 END)) AS 'Avg',
        SUM(CASE WHEN rating IS NULL THEN 1 ELSE 0 END) AS 'Unrated'
 From callrecord