sql - 如何组合来自两个不同日期范围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...
解决方案
您可以尝试使用过滤器。我冒昧地选择了您似乎想要的日期而不是完整日期。
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
推荐阅读
- r - 使用 r 中的 Oauth2 在 403 代码后授权访问 Xero
- c++ - C++ Prime Plus 6th
- javascript - 提示用户输入姓名和年龄并相应打印结果的 JavaScript 程序
- python - 如何在不使用虚拟机的情况下在 Windows 上将 .py 文件转换为 .apk 文件
- reactjs - 我需要在 React 和 Redux 中创建无限滚动吗?
- codeigniter - 我正在制作一个关于我们的页面,我需要使用 codeigniter 在单击数据库时更新三个图像以实现任务愿景和 about_us
- arrays - MATLAB:如何生成每行和每列具有特定数量 1 的随机二进制矩阵?
- jquery - 计算格式为 12 小时(上午,下午)的员工的工作时间
- kubernetes - 我可以清除 Kubernetes 中部署的历史修订吗?
- r - 我无法在我的图表中看到 xy 轴标签和 annotation_logticks,有什么建议吗?