按指定返回所有捐助者的最高SUM值

时间:2018-08-31 14:42:23

标签: sql oracle sum row-number

我有以下脚本:

SELECT DISTINCT GIFT_ID, GIFT_DESG, SUM(GIFT_AMT)
FROM GIFT_TABLE
GROUP BY GIFT_ID, GIFT_DESG

它将返回如下内容:

GIFT_ID         GIFT_DESG      SUM(GIFT_AMT)
      1                A               25
      1                B              500
      1                C               75
      2                A              100
      2                B              200
      2                C              300
      ...

我想要的结果是:

GIFT_ID         GIFT_DESG      SUM(GIFT_AMT)
      1                B           500
      2                C           300

我该怎么做?

可能是row_number()对吗?我认为这与按指定加总礼物金额有关,这使我不满意。

谢谢。

3 个答案:

答案 0 :(得分:1)

如果您的DBMS支持ROW_NUMBER窗口功能,则可以尝试按GIFT_ID的顺序按SUM(GIFT_AMT)的顺序创建行号,然后获取rn = 1的行。

SELECT t1.GIFT_ID,t1.GIFT_DESG,t1.GIFT_AMT 
FROM (
    SELECT t1.*,ROW_NUMBER() OVER(PARTITION BY GIFT_ID ORDER BY GIFT_AMT DESC) rn
    FROM (
      SELECT  GIFT_ID, GIFT_DESG, SUM(GIFT_AMT) GIFT_AMT
      FROM GIFT_TABLE
      GROUP BY GIFT_ID, GIFT_DESG
    ) t1
) t1
where rn =1

注意

您已经使用GROUP BY了,DISTINCT关键字是没有意义的,可以将其从查询中删除。


这是一个样本

CREATE TABLE T(
   GIFT_ID int,
   GIFT_DESG varchar(5),
  GIFT_AMT int
);


insert into t values (1,'A' ,25);
insert into t values (1,'B' ,500);
insert into t values (1,'C' ,75);
insert into t values (2,'A' ,100);
insert into t values (2,'B' ,200);
insert into t values (2,'C' ,300);

查询1

SELECT t1.GIFT_ID,t1.GIFT_DESG,t1.GIFT_AMT 
FROM (
    SELECT t1.*,ROW_NUMBER() OVER(PARTITION BY GIFT_ID ORDER BY GIFT_AMT DESC) rn
    FROM T t1
) t1
where rn =1

Results

| GIFT_ID | GIFT_DESG | GIFT_AMT |
|---------|-----------|----------|
|       1 |         B |      500 |
|       2 |         C |      300 |

答案 1 :(得分:0)

您可以不使用子查询来执行此操作:

SELECT TOP (1) WITH TIES GIFT_ID, GIFT_DESG, SUM(GIFT_AMT)
FROM GIFT_TABLE
GROUP BY GIFT_ID, GIFT_DESG
ORDER BY ROW_NUMBER() OVER (PARTITION BY GIFT_ID ORDER BY SUM(GIFT_AMT) DESC);

答案 2 :(得分:0)

您也可以这样

WITH t as
   SELECT GIFT_ID, GIFT_DESG, SUM(GIFT_AMT) AS GIFT_AMT
   FROM GIFT_TABLE
   GROUP BY GIFT_ID, GIFT_DESG)
SELECT  GIFT_ID, 
   max(GIFT_DESG) KEEP (DENSE_RANK LAST ORDER BY GIFT_AMT), 
   max(GIFT_AMT) GIFT_AMT
FROM T
GROUP BY GIFT_ID;