0

This might be simple but I'm new to SQL and couldn't find how to do this exactly.

and I have following table:

Existing table in SQL

My requirement is follows:

I need, for every Dim, for each Frequency, I need latest Date & maximum Version of that latest Date. For example: There will be one row for Dim 'A' & Frequency 'Monthly' with their latest Date & the latest date's maximum Version. and There will be another row for Dim 'A' & Frequency 'Weekly' with their latest Date & the latest date's maximum Version.

Can anybody please help me with this?

I tried using following query but it not returning correct values:

SELECT Dim, Frequency, Date, Version
               FROM   sample_tbl 
               WHERE  ( Frequency, Date, 
                        Version ) IN ( 
select Frequency, max(Date), max(Version)
from sample_tbl
group by 1
);
3

1 Answer 1

1

I Postgres, I think distinct on does what you want:

select distinct on (dim, frequency) s.*
from sample_tbl s
order by dim, frequency, date desc, version desc;

For each dim/frequency combination this returns one row. That row is the first row encountered based on the order by clause.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Gordon. Is there way where I can get the latest Date for 'monthly' & latest Date for 'weekly' frequencies and pick all rows for Dim where Date & Frequency are whatever we got in earlier?
@ParikshitShinge . . . Ask another question with appropriate sample data and desired results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.