最大一个分区的总和

Max a Sum of a partition by

我有以下 table。

我想对小时数求和并按 id 进行分区,然后对每个 custid 取 Max 小时数。以下是我到目前为止所拥有的。

表A

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

SQL:

select SUM(HOURS)OVER (PARTITION BY ID ORDER BY cust) AS TOTAL_HRS
from tablea

预期输出:以上 SQL 未捕获 MAX 小时

id    custid  projid  hours
 1      1010   Yellow  6

你还想要一个partition :

select *, sum(hours) over (partition by id, custid, projid order by cust) AS TOTAL_HRS
from tablea t
order by sum(hours) over (partition by id, custid, projid order by cust) desc
fetch first 1 row only;

SUM用作解析函数通常意味着您希望在保留所有原始记录的同时求和。但是您的预期输出似乎意味着聚合。所以,我建议使用 GROUP BY,然后查询它以找到时间最长的行。

WITH cte AS (
    SELECT id, custid, projid, SUM(hours) AS hours
    FROM yourTable
    GROUP BY id, custid, projid
)

SELECT *
FROM cte
ORDER BY hours DESC
WHERE rownum = 1

我想知道这是否符合您的要求:

select cust, sum(hours) as total_hours
from tablea
order by sum(hours)
fetch first 1 row only;

不清楚为什么需要该行中的其他值。如果这样做,您可以将它们聚合成一行。