【问题标题】:How i can get the max value of a sum of multiple columns in SQL?如何获得 SQL 中多列总和的最大值?
【发布时间】:2016-04-27 23:25:55
【问题描述】:

我的桌子

Name  column1 column2 column3
Julio 24      25      35
Jaime 30      40      35

这是我的查询

Select a.name, max(column1+column2+column3) from table group by name

如何获得多列总和的最大值?

【问题讨论】:

  • sqlserver, oracle, mysql, .. ?

标签: sql oracle sum


【解决方案1】:

我在 SQL Server 2014 中执行了这个查询。 希望对你有帮助

select name, max(column1+column2+column3) as MaxSum from table
group by name
having max(column1+column2+column3)= (select max(column1+column2+column3) from table)

【讨论】:

    【解决方案2】:

    根据你的查询

    select a.name, max(column1+column2+column3) from table group by name
    

    结果将是所有名称及其列的总和,假设每个名称都有一个对应的行。

    如果需要求和最大值对应的名称,请使用

    select name, column1+column2+column3 as sum
    from table t
    join (select max(column1+column2+column3) as maxsum from table) t1
    on t.column1+column2+column3 = t1.maxsum
    

    为了获得最大总和使用

    select max(column1+column2+column3) as maxsum from table
    

    【讨论】:

    • 备注: 与 maxsum 连接可能会在相等时产生多行。
    • 是的..以及最初在应用程序逻辑中经常被遗忘的内容
    【解决方案3】:

    我会使用 order byfetch first 1 row only(在 Oracle 12+ 中)来解决这个问题:

    Select a.name,
           sum(coalesce(column1, 0) + coalesce(column2, 0) + coalesce(column3, 0)) as s
    from table
    group by a.name
    order by sum(coalesce(column1, 0) + coalesce(column2, 0) + coalesce(column3, 0))  desc
    fetch first 1 row only;
    

    在早期版本中,使用子查询:

    select t.*
    from (Select a.name,
                 sum(coalesce(column1, 0) + coalesce(column2, 0) + coalesce(column3, 0)) as s
          from table
          group by a.name
          order by sum(coalesce(column1, 0) + coalesce(column2, 0) + coalesce(column3, 0))  desc
         ) t
    where rownum = 1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2019-03-16
      • 1970-01-01
      • 2019-11-21
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多