【问题标题】:PostgreSQL - Find number of installs each day given a table of installs and uninstallsPostgreSQL - 在给定安装和卸载表的情况下查找每天的安装次数
【发布时间】:2021-06-12 15:47:48
【问题描述】:

我有一个这样的机器安装表:

installationID, machineID, installed_at, uninstalled_at
A, 1, 2020-01-01, Null
B, 2, 2020-01-01, 2020-01-02
C, 3, 2020-01-02, Null
D, 2, 2020-01-04, Null

我需要一个查询来返回每天安装的机器数量。 像这样:

Date, installed
2020-01-01, 2
2020-01-02, 3
2020-01-03, 2 
2020-01-04, 3

我知道给定一个日期,比如“2020-01-03”,我可以得到安装机器的数量,如下所示:

SELECT date, count(machineID) 
from installs 
where installed_at >= '2020-01-03' 
and (uninstalled_at is Null or uninstalled_at <= '2020-01-03')

但是,我不知道如何以这样一种方式进行查询,以便在一次查询中获得所有日期的结果。

【问题讨论】:

标签: sql database postgresql


【解决方案1】:

使用从 2020 年 1 月 1 日到 2020 年 1 月 15 日生成的系列。根据需要调整“”。

select generate_series dt, count(*) n
from  generate_series('2020-01-01'::timestamp , '2020-01-15'::timestamp, '1 day')  
left join tbl on installed_at <= generate_series and ( uninstalled_at is null or uninstalled_at > generate_series)
group by generate_series
order by generate_series;

【讨论】:

  • 嗯...这似乎有效,但我正在使用 redshift,我得到FeatureNotSupported: Specified types or functions (one per INFO message) not supported on Redshift tables 我猜 redshift 不像我想象的那样接近 postgresql
  • 这个人遇到了和我在 redshift 上一样的问题:stackoverflow.com/questions/42102019/error-in-query-to-redshift
【解决方案2】:

您可以使用generate_series() 来生成日期。然后left joingroup by 来统计安装:

select gs.date, count(i.installationId)
from generate_series('2020-01-01'::date, '2020-01-04'::date, interval '1 day') gs(date) left join
     installations i
     on i.installed_at >= gs.date and
        9i.uninstalled_at > gs.date or i.uninstalled_at is null)
group by gs.date
order by gs.date;

注意:您似乎将卸载日期计为“安装”。我希望这不算数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-07
    • 2019-12-13
    • 2012-03-01
    • 2017-10-14
    • 2015-03-08
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多