SQL largest date of a record before the given date

1

Next has the following case:

Tb_importacao [cod_titulo,data,imp_situacao]

cod_titulo   data_imp    situacao
1           2015-04-10      1
1           2015-04-11      2
1           2015-04-11      1
1           2015-04-13      2
1           2015-04-14      3
1           2015-04-14      4

I need the highest date that has a 1% situation with%. My actual table has more than one title_code ...

Vlw!

    
asked by anonymous 16.04.2015 / 19:26

3 answers

3

Going by parts:

  • Select the largest data_imp = > MAX(data_Imp)
  • When data_imp is less than 2015-04-13
    and the situation is 1 = > WHERE data_imp < '2015-04-13' AND situacao = 1
  • For each tag_code => GROUP BY cod_titulo

Putting it all together:

SELECT cod_titulo, MAX(data_imp) FROM tb_importacao 
WHERE data_imp < '2015-04-13' AND situacao = 1
GROUP BY cod_titulo
    
16.04.2015 / 19:39
1

Could you test this SQL? I was going to leave it in the comments but it's too big. You may need some adaptation yet to get the exact result you need. Just let us know that we're modeling it. (I can not test)

SELECT imp1.cod_titulo, MAX(imp2.data_imp) as data_ativa, MAX(imp3.data_imp) as data_inativa FROM tb_importacao as imp1
JOIN tb_importacao as imp2 ON imp2.situacao = 1
JOIN tb_importacao as imp3 ON imp3.situacao = 2
WHERE imp1.data_imp < '2015-04-13'
GROUP BY cod_titulo

In case it will return two dates. The highest active date (date_active) and the highest date inactive (date_inativa), so you compare to your target date in the schedule.

    
16.04.2015 / 19:59
-1

Try using the GREATEST function.

select greatest(col1, col2, col3, col4) from tab1; 
    
09.08.2018 / 17:04