Solved

Selecting all records that have a max value in another column?

Posted on 2008-11-02
4
356 Views
Last Modified: 2009-07-18
Hi there,
I have a table where I want to retrieve all the records that have a maximum modified date for a particular fact:

FACT_ID, FACT1, MODIFIED_DATE ... (100 other facts)
1, A, 2008-01-01 00:00:00.000
2, A, 2008-02-01 00:00:00.005
3, A, 2008-02-01 00:00:00.005
4, B, 2007-01-01 00:00:00.000
5, B, 2008-05-05 00:00:00.000

I would like the query to return rows 2, 3, and 5.. I've only been able to do this using a cursor so far iterating through all the fact_ids, but I'm sure there must be a set operation that can do this :)

Thanks,

Charles
0
Comment
Question by:cshlin
  • 2
4 Comments
 
LVL 9

Expert Comment

by:jamesgu
Comment Utility
select * from  a,
inner join (select FACT_ID, FACT1, max(MODIFIED_DATE) as max_MODIFIED_DATE from  group by FACT_ID, FACT1) b
where a.FACT_ID  = b. FACT_ID
and a. FACT1  = b. FACT1  
and a. MODIFIED_DATE = b. max_MODIFIED_DATE
0
 
LVL 9

Accepted Solution

by:
jamesgu earned 63 total points
Comment Utility
try this one instead of the previous

select * from  a,
inner join (select FACT1, max(MODIFIED_DATE) as max_MODIFIED_DATE from  group by FACT1) b
where a.FACT_ID  = b. FACT_ID
and a. MODIFIED_DATE = b. max_MODIFIED_DATE
0
 
LVL 39

Assisted Solution

by:BrandonGalderisi
BrandonGalderisi earned 62 total points
Comment Utility
Try this:

with RankedData as
(select *,dense_rank() over(partition by fact1 order by modified_date desc) dr from YourTable)
select * from RankedData
where dr=1
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the fileā€¦
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now