• Status: Solved
• Priority: Medium
• Security: Public
• Views: 367

# MAX of two columns in one SQL

Hello,
I have the following Customer table:

The desired output is:
CustomerId = 1
OrderDate = 02-FEB-2014
CustomerEmail = angel@yahoo.com

I need to get the latest order date and related email from this table.

I tried to do the following:
``````Select CustomerId, MAX(OrderDate) OVER (PARTITION BY CustomerID), MAX(CustomerEmail) OVER (PARTITION BY CustomerId)
FROM Customer table;
``````

Though this sql is returning the MAX(orderDate) correctly, the MAX(CustomerEmail) returned is not the one associated to the Max(orderdate) but the one with highest alphabetical order (i.e, in this case Zy2013@yahoo.com).

How do I get both the MAX(OrderDate) and its associated CustomerEmail in the same query using MAX as well as OVER PARTITION by approach?

Thanks!
0
sath350163
• 2
2 Solutions

Commented:
Select CustomerId, MAX(OrderDate),CustomerEmail  OVER (PARTITION BY OrderDate), FROM Customer table;
0

Commented:
If my understanding is correct, your logical requirement is to identify latest order by each customer and then get the related value.  So partition by should be based on CustomerID and OrderBy should be based on orderDate

ROW_number is the proper function for this requirement, something similar to the following would be useful.

``````select *
from
(  select * ,
row_number () over ( partition by customerid order by orderdate desc )  as rownum
from customer
) DTab
where rownum = 1
``````
0

Commented:
There are a couple of ways of doing that this is one:
``````SELECT  c.CustomerId, c.OrderDate, c.CustomerEmail
FROM    [Customer table] c
INNER JOIN (SELECT  CustomerId,
MAX(OrderDate) LastOrderDate
FROM    [Customer table]
GROUP BY CustomerId
) d ON c.CustomerId = d.CustomerId
AND c.OrderDate = d.LastOrderDate
``````
0

Commented:
Here is another approach using a CTE:
``````;WITH    CTE
AS (SELECT    CustomerId,
OrderDate,
CustomerEmail,
ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY OrderDate DESC) Row
)
SELECT  CustomerId,
OrderDate,
CustomerEmail
FROM    CTE
WHERE   Row = 1
``````
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.