【问题标题】:Fetch 0 for the rows which does not have any data为没有任何数据的行获取 0
【发布时间】:2021-08-04 10:36:27
【问题描述】:

我们有一个用户注册表,其中注册计数按月存储。每个month_key 将只有一行。

我们还有一个employer_key 列。每个employer_key 都会有(10 或8 或4 或12 个月)的数据。

这是一个 postgreSQL 表。

month_key registration_count
202107 32
202103 19
202012 05
202008 54

我的要求是提取每个雇主过去 12 个月的总注册数。月份范围将根据当前月份而有所不同。

如果任何特定月份没有注册计数数据,则为其显示 0。我们可以使用 PostgreSQL 查询吗?

现在我已经写了一个简单的查询,比如 -

select month_key, registration_count
from user_registrations ur 
where employer_key = 101 
and month_key between 202008 and 202107;

这个查询只返回那些有数据的行。谁能帮我解决一下。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    您可以生成您想要的月份并离开加入。由于月份键,这有点棘手。假设它是一个整数:

    select month_key, coalesce(ur.user_registrations, 0)
    from (select yyyymm,
                 to_char(yyyymm, 'YYYYMM')::int as month_key
          from generate_series(date_trunc('month', now()) - interval '11 month', 
                               date_trunc('month', now()),
                               interval '1 month'
                              ) gs(yyyymm)
          ) ym left join
          user_registrations ur
          using (month_key);
    

    如果month_key 是字符串,您将使用类似的逻辑,但子查询将删除::int 以使用字符串。

    【讨论】:

    • month_key 是整数。
    • 此查询有效,但不完全正确。它返回 16 行,而不是 12 行。有几个月它返回多行。
    • @sandeep 。 . .如果 user_registrations 在一个月内有多行,这只会返回多行。您的问题没有暗示这是可能的,没有描述您想要的逻辑,并且您的示例数据没有重复。解决方案是使用group by month_key 和适当的聚合。该问题明确指出:“我有一个用户注册表,其中注册计数按月存储。”
    • 好的...为了更好地理解,我对我的问题进行了一些更改。你能看一下吗?
    猜你喜欢
    • 2021-10-29
    • 2017-09-22
    • 1970-01-01
    • 2021-01-17
    • 2011-06-19
    • 2020-10-08
    • 1970-01-01
    • 2015-10-05
    • 2022-12-26
    相关资源
    最近更新 更多