You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中如何按客户(redirect)和来源统计唯一月份的发票数量

PostgreSQL按客户和来源统计发票月度发行数量的正确查询

原查询的问题在于使用count(case...)时,else 0会让不匹配条件的行也被计入统计,导致结果是该来源的总行数而非有数据的月份数;而max仅返回最大月份值,无法满足统计月份数量的需求。

正确的做法是使用count(distinct ...),仅统计匹配来源的不同月份数量,不匹配时返回null(省略else分支),count(distinct)会自动忽略null值,从而得到有发票发行的月份总数。

修正后的查询语句

select 
  TA.redirect, 
  count(distinct case when TA.source='zlat1' then extract(month from TA.date) end) as number_of_accounts_zlat1,  
  count(distinct case when TA.source='zlat2' then extract(month from TA.date) end) as number_of_accounts_zlat2,  
  sum(TA.result_for_the_day) as accrued
from total_accounts TA
group by TA.redirect;

逻辑说明

  • count(distinct case when TA.source='zlat1' then extract(month from TA.date) end):仅对source='zlat1'的行提取月份,统计这些月份的去重数量,即该客户zlat1来源有发票发行的月份数。
  • 省略else分支时,不匹配条件的行返回null,count(distinct)不会将null计入统计,避免了无效数据干扰。
  • sum(TA.result_for_the_day)保持原逻辑,累加客户的总金额。

内容的提问来源于stack exchange,提问作者Alexey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 12:45:41