为具有两列一组的列选择MAX SUM(最高第一组仅由第一列构成)

时间:2018-10-20 22:28:58

标签: sql common-table-expression

Table querying on:
COL1        COL2    COL3 
ABC1        ORG1    1.5
ABC1        ORG2    4.5
ABC1        ORG1    2.0
ABC1        ORG2    3.0
ABC1        ORG3    1.0
ABC1        ORG3    5.5
ABC1        ORG3    2.5
ABC1        ORG4    40.0
ABC2        ORG1    1.5
ABC2        ORG2    5.0
ABC2        ORG1    2.0
ABC2        ORG2    25.0
ABC2        ORG3    1.0
ABC2        ORG3    5.5
ABC2        ORG3    2.5
ABC2        ORG4    20.0
ABC3        ORG1    15.5
ABC3        ORG2    4.5
ABC3        ORG1    5.0
ABC3        ORG2    3.0
ABC3        ORG3    1.0
ABC3        ORG3    5.5
ABC3        ORG3    2.5
ABC3        ORG4    10.0


Output:
COL1        COL2    COL3 
ABC1        ORG4    40.0
ABC2        ORG2    30.0
ABC3        ORG1    20.5

我需要先计算第3列之和并为第2列选择max的输出,但输出中也显示col1,如输出所示。我尝试了开窗,但是当我运行它进行一百万条记录时似乎很慢,并且想知道如何优化它或如何将其与rownumber函数一起使用:

select * from
    (select col1, col2
      , sum(col3) as Tot
      , max(sum(col3)) over (partition by col1) as MSum
      from table1
    group by col1, col2)
a
where a.tot = a.Msum

0 个答案:

没有答案