首页 > 解决方案 > 补齐 SQL 查询中的空白

问题描述

假设我们有一个包含以下内容的表:

PlayerID     Number_of_Awards

每个 playerID 都是不同的。没有重复。

对于每个奖项的数量,我想看看玩家人数。

select number_of_awards, count(playerid) as cnt from table group by number_of_awards

但是,当我得到输出

 number_of_awards     cnt

       2               10
       3               2
       4               3
       6               1

我有上表。1, 5 缺失,因为没有玩家只获得一个或 5 个奖项。

我想填补这个空白。我希望输出是

 number_of_awards     cnt

       1               0
       2               10
       3               2
       4               3
       5               0
       6               1

有没有填补这种空白的sql函数?我们该怎么做呢?

标签: sql

解决方案


一个常见的技巧是使用包含“合理”数字范围的数字表。

例如,

create table Numbers (
    N int primary key clustered not null
);
insert into Numbers Values (1, 2, 3, ..., <A reasonable value>);

然后,您可以加入此表。

select
    num.N
    , award_cnt.cnt
from
    Numbers as num
left join
    (
    select number_of_awards, count(playerid) as cnt from table group by number_of_awards
    ) as award_cnt
    on
        num.N = award_cnt.number_of_awards
order by
    num.N

推荐阅读