如何合并来自两个不同日期范围 sql 的两个不同计数

How to combine two different counts from two different date ranges sql

我会尽量保持简单。

我有两个查询运行良好,它们都统计了当天在特定日期范围内注册的用户数。

查询 1 - 获取从今天起每年的每一天都注册的用户列表。这是结果的 picture。

SELECT users.created::date,
       count(users.id)
FROM users
WHERE users.created::date < now() - interval '12 month'
  AND users.created::date > now() - interval '13 month'
  AND users.thirdpartyid = 100
GROUP BY users.created::date
ORDER BY users.created::date

查询 2 - 获取一个月前从今天开始每天注册的用户列表。这是此结果的 picture。

SELECT users.created::date,
       count(users.id)
FROM users
WHERE users.created::date > now() - interval '1 month'
  AND users.thirdpartyid = 100
GROUP BY users.created::date
ORDER BY users.created::date

我坚持的是如何将这两个查询组合起来,以便我可以在我的 redash 网站上创建一个堆栈条形图。它们显然都是不同的年份,但我希望我的 X 轴是该月的日期,Y 轴是用户数。谢谢。

编辑:

这是一个我认为非常适合我的示例输出。

|本月第几天 |用户于 2017 年 12 月注册 | 2018 年 12 月注册的用户
|-------------------- | -------------------------- | ------------------------------|
| 01 45 56
| ------------------ | -------------------------- | ------------------------------|
| 02 47 32
| ------------------ | -------------------------- | ------------------------------|

ETC...

您可以尝试使用过滤器。我冒昧地选择 select 月份中的第几天,因为您似乎想要那个而不是完整的日期。

SELECT date_part('day', users.created::date) as day_of_month,
       count(users.id) FILTER (
           WHERE users.created::date < now() - interval '12 month'
           AND users.created::date > now() - interval '13 month') AS month_12,
       count(users.id) FILTER (
           WHERE users.created::date > now() - interval '1 month') AS month_1
FROM users
WHERE (
       (
            users.created::date < now() - interval '12 month'
        AND users.created::date > now() - interval '13 month'
       ) OR users.created::date > now() - interval '1 month'
      )
  AND users.thirdpartyid = 100
GROUP BY day_of_month
ORDER BY day_of_month