Extract Previous Month Date in SQL

 If you are working  on Spark SQL and you want to extract previous month last date from existing date and unfortunately your present date in  text format e.g '20230301'


Problem : You have column called "process_date" which contain date like '20230310' (March) and in same table you you have another date in same column have date like '20230228' (Feb) which is the last date of previous month. 


 Existing date -  '20230310'  
Requirement :- To extract '20230228' (Last date of previous month)


select 
   process_date
  from table1
   where  process_date = 
                 (
                    select max(process_date) 
                                          from table1
                                             where to_date(process_date, 'yyyyMMdd') 
                                                          <  to_date(substring('20230310',0,6),'yyyyMM') 
                      ) 

Comments

Popular posts from this blog

Date format issue with spark sql

Hive Partition sub folders HIVE_UNION_SUBDIR_1,HIVE_UNION_SUBDIR_2,HIVE_UNION_SUBDIR_8

Dataiku and Dremio date difference