SQL - Postgres - return maximum value for latest date [duplicate]

折月煮酒 提交于 2019-12-24 19:13:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!