PostgreSQL查询2021年起每月同时在上月和当月下单的客户数
问题分析与解决方案
你的查询无法正常运行的核心问题有两个:
- 子查询未区分内外层表字段:子查询里的
month_column没有指定所属表,导致month_column = month_column - INTERVAL '1 month'永远不成立(同一字段不可能等于自身减一个月),子查询返回空集后最终结果也为空。 - 表名使用关键字:
table是PostgreSQL的保留关键字,不能直接作为表名使用。
结合你统计「每个月同时在上月和当月下单的客户数量」的需求,以及month_column存储每月第一天的特点,这里提供两种可行方案:
方案一:自连接实现
通过表自连接匹配当月与上月的同一客户记录:
SELECT t_current.month_column AS current_month, COUNT(DISTINCT t_current.customer_id) AS repeat_customer_count FROM your_table t_current JOIN your_table t_prev ON t_current.customer_id = t_prev.customer_id AND t_prev.month_column = t_current.month_column - INTERVAL '1 month' WHERE t_current.month_column >= '2021-01-01' GROUP BY t_current.month_column ORDER BY t_current.month_column;
方案二:EXISTS子查询修正
基于你原有思路优化,明确关联外层表的月份字段:
SELECT month_column AS current_month, COUNT(DISTINCT customer_id) AS repeat_customer_count FROM your_table t WHERE month_column >= '2021-01-01' AND EXISTS ( SELECT 1 FROM your_table t_prev WHERE t_prev.customer_id = t.customer_id AND t_prev.month_column = t.month_column - INTERVAL '1 month' ) GROUP BY month_column ORDER BY month_column;
关键提示
- 请将上述查询中的
your_table替换为你实际使用的表名。 - 由于
month_column已经是每月第一天,无需再用DATE_TRUNC('month', month_column)处理,直接使用字段即可。
内容的提问来源于stack exchange,提问作者sql_bro
相关产品推荐
相关产品推荐

