首页 > 解决方案 > 如何组合来自两个不同日期范围sql的两个不同计数

问题描述

我会尽量保持简单。

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

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

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 - 获取从今天开始一个月前每天注册的用户列表。这是这个结果的图片

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...

标签: sqlpostgresqlredash

解决方案


您可以尝试使用过滤器。我冒昧地选择了您似乎想要的日期而不是完整日期。

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

推荐阅读