Q
Manage Learn to apply best practices and optimize your operations.

# How to use the SQL MAX function to sum the values of a column

## SQL expert Karen Morton explains how to use the SQL MAX function to sum the values of one column based on comparison with another in this expert tip.

How do I sum the values of a column based on a comparison with another column?

Eg., I have columns num1, num2, val, sumval.

I want to group num1 and num2 columns and get sum(sumval), and this sum should happen for max(val) = val in the same table.

create table tempval(num1 number, num2 number, val number, sumval number);

```insert into tempval values(111, 222, 1, 10);
insert into tempval values(111, 222, 1, 20);
insert into tempval values(111, 222, 2, 30);
insert into tempval values(111, 222, 2, 40);
insert into tempval values(111, 333, 1, 15);
insert into tempval values(111, 333, 4, 25);
```

In the above, I need to get the output as two records as like below:

```A. 111, 222, 70		(70 is the sum value based on 2 records since 2 is max for this group.
B. 111, 333, 25		(25 is the sum value based on 1 record since 4 is max value for this group)
```

Try this:

```SQL>create table tempval(num1 number, num2 number, val number, sumval number);

Table created.

SQL>
SQL>insert into tempval values(111, 222, 1, 10);

1 row created.

SQL>insert into tempval values(111, 222, 1, 20);

1 row created.

SQL>insert into tempval values(111, 222, 2, 30);

1 row created.

SQL>insert into tempval values(111, 222, 2, 40);

1 row created.

SQL>insert into tempval values(111, 333, 1, 15);

1 row created.

SQL>insert into tempval values(111, 333, 4, 25);

1 row created.

SQL>commit ;

Commit complete.
```

I'm executing this query first to show you how the final answer is built. I use the MAX analytic function to compute the MAX val column value for each grouping of num1, num2.

```SQL>select num1, num2, val, sumval,
2  max(val) over (partition by num1, num2) max_val
3  from tempval ;

NUM1            NUM2             VAL          SUMVAL         MAX_VAL
--------------- --------------- --------------- --------------- ---------------
111             222               1              10               2
111             222               1              20               2
111             222               2              30               2
111             222               2              40               2
111             333               1              15               4
111             333               4              25               4

6 rows selected.
```

Now, all I have to do is create a filter predicate that only retains rows where the VAL and MAX_VAL match and then group things up and do the final SUM.

```SQL>
SQL>select num1, num2, sum(sumval) totsum
2  from
3  (
4  select  num1, num2, val, sumval,
5     max(val) over (partition by num1, num2) max_val
6  from tempval
7  )
8  where val = max_val
9  group by num1, num2
10  ;

NUM1            NUM2          TOTSUM
--------------- --------------- ---------------
111             222              70
111             333              25

2 rows selected.
```

Have a question for Karen Morton? Send an e-mail to editor@searchoracle.com

This was last published in April 2010

## Content

Find more PRO+ content and other member only offers, here.

#### Have a question for an expert?

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

### 1 comment

Send me notifications when other members comment.
How do i retrieve the Max value of two table?

Ex: i have two source table like crmd_order and crmd_order_h
from these two table i have to get the max value of SLTTMESTAMP
column is same in both tables.

Cancel

## SearchDataManagement

• ### Hyperledger Fabric offers path to enterprise blockchain future

Blockchain arose from bitcoin, but it's looking to find a place in the enterprise. Frameworks like Hyperledger Fabric could ...

• ### MongoDB 4.0 takes ACID transactions to multi-document level

MongoDB is taking a deeper step into SQL-style processing waters with a 4.0 update that brings increased support for ...

• ### Data lake concept needs firm hand to pay big data dividends

Data lakes pose technology deployment and data management challenges that can leave analytics users high and dry if the ...

• ### AI functionality limited today but could be a game-changer

Limited AI capabilities could soon give way to technology that is truly transformative for enterprises, surpassing the overhyped ...

## SearchSAP

• ### ControlPanelGRC app eases Steelcase's compliance pain

When Steelcase's SAP environment grew in size and complexity, it turned to Symmetry ControlPanelGRC to save time, have more ...

• ### Translytical data platforms emerge with SAP HANA as a leader

SAP HANA is a leading translytical platform, according to Forrester, and consulting firm Convergent IS says the combination of ...

• ### SAP HANA and Esri combine for geospatial database platform

SAP and Esri are combining SAP HANA's in-memory database capabilities with Esri geospatial applications, and utilities are taking...

## SearchSQLServer

SQL Operations Studio simplifies routine administration of SQL Server and Azure SQL databases, making database development and ...

• ### Meltdown and Spectre fixes eyed for SQL Server performance issues

Microsoft has responded to the Spectre and Meltdown chip vulnerabilities with patches and other fixes. But IT teams need to sort ...

• ### Five SQL Server maintenance steps you should take -- ASAP

Putting off SQL Server administration tasks can lead to database problems. Enact these often-neglected maintenance items to help ...

## TheServerSide.com

• ### Pluralsight IQ, Stack Overflow boost developer street cred

Tying the Pluralsight IQ skills test to the Stack Overflow Developer Story helps developers measure their technical skills and ...

• ### Why this quantum computing breakthrough is a security risk

Quantum computing will void pretty much all security encryption techniques and open the door to hackers. Here's how to protect ...

• ### Database automation drives DevOps into the persistence layer

A new breed of software tools is driving DevOps processes deep into the persistence layer, as database automation and continuous ...

## SearchDataCenter

• ### Evaluate read-intensive and write-intensive SSD use cases

Consider write wear, performance and other factors when choosing between read-intensive, write-intensive and mixed-use ...

• ### Some hyper-converged infrastructure use cases pose pitfalls

Hyper-converged infrastructure adoption is skyrocketing, but that doesn't mean that the technology is the best choice for every ...

• ### Dell hyper-converged reorg streamlines products, ups CI odds

Market pressures and manufacturing synergies drove Dell to integrate its HCI and CI products with its core business units, but ...

## SearchContentManagement

• ### Content management in the cloud a main theme in 2018

The future of content management resides in the cloud and with AI, as several 2018 conferences will assure you.

• ### Six things to know about today's SharePoint implementations

As companies migrate their on-premises Microsoft SharePoint sites to the cloud, here are some things they should know about the ...

• ### Upgrades for the SharePoint Online portal

As more organizations migrate SharePoint sites to the cloud, Microsoft has increased at-a-glance dashboard data and analytics to ...

## SearchHRSoftware

• ### Don't overlook the many benefits of Microsoft Excel for HR

The maligned spreadsheet tool is no substitute for enterprise apps like HRMS and people analytics, but it will do in a pinch and ...

• ### HR is failing to use people analytics tools, new report says

Human resource departments fail to use people analytics tools effectively, a new global study concludes. The findings were called...

• ### Does your company need new human resource management tools?

Finding the best human resource management tools starts with identifying your company's present and future needs, before ...

Close