PostgreSQL季度查询条件异常:1月数据未被聚合的原因排查
问题原因与解决方案
核心原因:字符串字典序比较的坑
你把data_bas_year和data_bas_month拼接成了6位字符串(比如1月是'202101'),但WHERE条件里用它和8位的'20210101'做BETWEEN比较——PostgreSQL中字符串比较是按字典序逐字符对比,当两个字符串长度不同时,会把短字符串补空字符后再比。
'202101'和'20210101'前6位完全一致,但'202101'后面是空字符,空字符的ASCII码小于数字0,所以'202101' < '20210101',导致2021年1月的数据被WHERE条件过滤掉了,自然不会出现在第一季度的统计结果里。
而改成'20201231'时,'202101'的前4位'2021'大于'2020',所以'202101' > '20201231',1月数据就能被包含进来。
正确的写法建议
别用字符串拼接做日期范围判断,直接用日期类型或数值比较更靠谱:
方案1:直接比较年和月的数值
SELECT (outbound.data_bas_year||outbound.data_bas_month) as year_month, EXTRACT(QUARTER from to_date(outbound.data_bas_year||outbound.data_bas_month, 'YYYYMM')) AS quarter, count(outbound.call_time) as col_1_0_ FROM cfk_dashboard.if_outbnd_call_dtl outbound WHERE outbound.data_bas_year = 2021 AND outbound.data_bas_month BETWEEN 1 AND 12 AND outbound.conn_call_number = 1 GROUP BY year_month,quarter
方案2:转成日期类型后比较
SELECT (outbound.data_bas_year||outbound.data_bas_month) as year_month, EXTRACT(QUARTER from to_date(outbound.data_bas_year||outbound.data_bas_month, 'YYYYMM')) AS quarter, count(outbound.call_time) as col_1_0_ FROM cfk_dashboard.if_outbnd_call_dtl outbound WHERE to_date(outbound.data_bas_year||outbound.data_bas_month, 'YYYYMM') BETWEEN '2021-01-01'::date AND '2021-12-31'::date AND outbound.conn_call_number = 1 GROUP BY year_month,quarter
注:把别名
year改成year_month更准确,避免和内置函数名冲突。
内容的提问来源于stack exchange,提问作者김진영
相关产品推荐
相关产品推荐

