代码之家  ›  专栏  ›  技术社区  ›  user98235

完成SQL查询中的空白

sql
  •  1
  • user98235  · 技术社区  · 6 年前

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

    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
    

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

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

    有没有一个sql函数来填补这个空白?我们怎么做?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Arulkumar KP.    6 年前

    你可以在下面试试-

    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
    
        2
  •  1
  •   gomory-chvatal    6 年前

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

    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
    
        3
  •  1
  •   Gordon Linoff    6 年前

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

    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() 这对这类问题很方便。