问题
This might be simple but I'm new to SQL and couldn't find how to do this exactly.
I have following table:

My requirement is follows:
I need, for each Frequency (monthly & weekly), pick latest Date & its maximum Version of that latest Date. Then select records for all Dim & both Frequencies where Date and Version are same as the earlier picked.
For example: There will single latest date & its maximum Version for 'Monthly' Frequency & single date & its maximum Version for 'Weekly' Frequency. Now for all Dim (A & B in our case), just return data where Date & Frequency are same as earlier.
So there will be total 4 rows:
- Dim 'A' Monthly
- Dim 'A' Weekly
- Dim 'B' Monthly
- Dim 'B' Weekly
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
);
回答1:
you could use a join with a subquery for get max date and then the max version
select s.Dim, s.Frequency, s.Date, max(s.Version)
from sample_tbl s
inner (
SELECT Dim, Frequency, max(Date) as max_date
FROM sample_tbl
group by Dim, Frequency
) t on t.Dim = s.Dim, t.Frequency = s.Frequency t.max_date = s.Date
GROUP BY s.Dim, s.Frequency, s.Date ;
来源:https://stackoverflow.com/questions/48023183/sql-postgres-return-maximum-value-for-latest-date