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

SQL技术需求:按id分区求和hours后取各custid的最大总和

解决SQL分组求和后取最大值的问题

让我帮你调整SQL语句,实现你想要的需求——先按id分区计算每个custid的hours总和,再找出总和最大的那条记录。

首先看你的原始数据:

原TableA表数据:

id custid projid hours
1  1010  Yellow 1
1  1011  Yellow 2
1  1012  Yellow 5
1  1010  Yellow 5

你之前的SQL语句存在几个问题:

  • 字段名拼写错误:ORDER BY cust应该是ORDER BY custid
  • 窗口函数的用法不对:SUM(HOURS) OVER (PARTITION BY ID ORDER BY custid)会生成每行的累计和,而不是按custid分组的总合
  • 缺少筛选最大总和的逻辑

正确的实现步骤

我们可以用CTE(公共表表达式)分两步完成:

第一步:计算每个custid的hours总和

先按id、custid、projid分组,计算每个客户的总工时:

WITH cust_total_hours AS (
    SELECT 
        id,
        custid,
        projid,
        SUM(hours) AS total_hrs
    FROM tablea
    GROUP BY id, custid, projid
)

这个CTE会得到如下中间结果:

id custid projid total_hrs
1  1010  Yellow 6
1  1011  Yellow 2
1  1012  Yellow 5

第二步:筛选出总和最大的记录

从上面的结果中,找出total_hrs最大的那条记录,有两种常用方式:

方式一:用MAX()子查询筛选
WITH cust_total_hours AS (
    SELECT 
        id,
        custid,
        projid,
        SUM(hours) AS total_hrs
    FROM tablea
    GROUP BY id, custid, projid
)
SELECT id, custid, projid, total_hrs AS hours
FROM cust_total_hours
WHERE total_hrs = (SELECT MAX(total_hrs) FROM cust_total_hours)
方式二:用窗口函数RANK()排序筛选

如果存在多个客户有相同的最大工时,这个方式可以保留所有符合条件的记录(如果只需要一条,可改用ROW_NUMBER()):

WITH cust_total_hours AS (
    SELECT 
        id,
        custid,
        projid,
        SUM(hours) AS total_hrs,
        RANK() OVER (ORDER BY SUM(hours) DESC) AS rank_num
    FROM tablea
    GROUP BY id, custid, projid
)
SELECT id, custid, projid, total_hrs AS hours
FROM cust_total_hours
WHERE rank_num = 1

两种方式最终都会得到你期望的输出:

id custid projid hours
1  1010  Yellow 6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:14:05