Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select max column value when column value does not exist?

I have a table with the following data below. I'm struggling with the sql to select the row with the max fiscal_period and fiscal_year if the where clause in my sql does not exist in the table.

so in other words , if i try to select fiscal year 8 which does not yet exist , my query should retrieve the row with the max period and year that does exist. can anyone help me with a query that would provide that answer?

here is what i tried so far.

    SELECT   
 nvl(FISCAL_PERIOD,max(FISCAL_PERIOD)),nvl(FISCAL_year,max(FISCAL_year)),amount  
        FROM MAXTABLE   
        where fiscal_period = 5  
        group by FISCAL_PERIOD,FISCAL_year, amount;


CREATE TABLE MAXTABLE  
   (    "FISCAL_PERIOD" NUMBER,  
         "FISCAL_YEAR" NUMBER,  
         "AMOUNT" NUMBER  
   ) 


 Insert into MAXTABLE (FISCAL_PERIOD,FISCAL_YEAR,AMOUNT) values (1,9,50);  
    Insert into MAXTABLE (FISCAL_PERIOD,FISCAL_YEAR,AMOUNT) values (2,5,50);  
    Insert into MAXTABLE (FISCAL_PERIOD,FISCAL_YEAR,AMOUNT) values (3,6,50);  
like image 858
Miguel Avatar asked Apr 23 '26 01:04

Miguel


1 Answers

Use a union all with the query to get data for the max year with an additional not exists condition for the target year, so both halves of the union can't be returned:

SELECT FISCAL_PERIOD, FISCAL_year, amount  
FROM MAXTABLE   
where fiscal_period = 5  
union all
SELECT FISCAL_PERIOD, FISCAL_year, amount  
FROM MAXTABLE 
where fiscal_period = (select max(fiscal_period) from MAXTABLE)
and not exists (select * from MAXTABLE where fiscal_period = 5)
like image 179
Bohemian Avatar answered Apr 25 '26 19:04

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!