sql - 补齐 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函数?我们该怎么做呢?
解决方案
一个常见的技巧是使用包含“合理”数字范围的数字表。
例如,
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
推荐阅读
- java - 如何修复 ProGuard 错误
- pyspark - pyspark sum 使用开始和结束日期按月份和日期分组
- ruby-on-rails - 如何使用 Ruby 生成两个地址之间的 IP 地址列表
- php - 将字符和数字之间的字符串拆分为数组PHP
- php - 删除 Woocommerce 帐单字段不会将其从我的帐户帐单地址中删除
- java - ConcreteA 不是抽象的,不会覆盖 InterfaceC 中的抽象方法 doSomething(InterfaceA)
- git - 将深度嵌套的 Rust `Result`s 和 `Option`s 处理重构为更具功能性的风格
- python - 如何控制plotnine中的刻面高度和宽度?
- sql - 根据与另一个表的几何相交将列数据添加到表中 - PostgreSQL
- machine-learning - Gensim 的潜在狄利克雷分配实现