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

按日期分组统计每日支付总额的SQL语句异常排查求助

问题排查与修正

你的SQL返回多余行数的核心原因是GROUP BY子句错误地包含了pmttotamt字段。

当你把pmttotamt加入分组条件时,数据库会将同一天且支付金额完全相同的记录归为一组,而不是把当天所有支付记录聚合求和。这就导致只要当天有不同金额的支付,就会生成多条分组结果,最终行数远超过31天。

修正后的SQL

通用版本(适配多数数据库)

select
  cast(date as date) as pay_date,
  sum(pmttotamt) as daily_total
from pmts
where year(date) = 2025
  and month(date) = 1
group by cast(date as date)

针对不同数据库的优化写法

  • SQL Server:
select
  convert(date, [date]) as pay_date,
  sum(pmttotamt) as daily_total
from pmts
where year([date]) = 2025
  and month([date]) = 1
group by convert(date, [date])
  • MySQL:
select
  date(date) as pay_date,
  sum(pmttotamt) as daily_total
from pmts
where year(date) = 2025
  and month(date) = 1
group by date(date)

额外说明

如果你的[date]字段只包含日期(无时分秒),也可以直接用group by [date],但建议显式转换为日期类型,避免因字段类型隐含的时间部分导致分组错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 15:13:11