填补SQL查询中的空白

时间:2019-05-03 04:01:32

标签: sql

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

PlayerID     Number_of_Awards

每个玩家ID是不同的。没有重复。

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

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个是因为没有玩家赢得一个或五个奖项。

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

 number_of_awards     cnt

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

是否存在填补此类空白的sql函数?我们该怎么做?

3 个答案:

答案 0 :(得分:1)

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

例如,

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

答案 1 :(得分:1)

您希望将其用于聚合,因此原始表具有所需的行。所以,我在想:

with naw as (
      select number_of_awards, count(playerid) as cnt
      from t
      group by number_of_awards
     ),
     n as (
      select n.n
      from (select row_number() over (order by playerid) as n
            from t
           ) n join
           (select max(number_of_awards) as maxn
            from naw
           ) maxn
           on n.n <= maxn
     )
select n.n, coalesce(cnt, 0) as cnt
from n left join
     naw
     on n.n = naw.number_of_awards
order by n.n;

根据数据库的不同,可能会有更简单的方法。例如,Postgres支持generate_series(),这种类型的问题很方便。

答案 2 :(得分:0)

您可以在下面尝试-

select A.val,coalesce(cnt,0) from
(
select 1 as val 
union 
select 2 
union 
select 3 union selecct 4 union select 5 union select 6
)A left join 
(select number_of_awards, count(playerid) as cnt from table group by number_of_awards)B
on A.val=B.number_of_awards