Please tell me there is such a table: 
Depending on the osn variable, you need to select rows grouped by vidv and maximum date:
- If osn = 3030, then select lines 12 and 13.
- If osn = 60090, then select lines 12 and 13.
- And if osn = 20370, then choose nothing, since there is a line with razdel = '3030', vidv = '1' and a later date.
Here is the code written, then stuck:
SELECT * FROM ( SELECT id, max(sroks), razdel, vidv FROM ( SELECT id, sroks, srokpo, replace (razdel,' ', '') as razdel, vidv FROM vpl.manrazdel ) GROUP BY id, razdel, vidv ) where id='037016034158607001409576221452' and "Код" IN (@osn) that's what it gives out:
I will try to translate into human language. You need to select the current razdel and vidv. Relevance is determined by date. Ie if there are several identical vidv, but with different razdel value, then the current vidv will be with a later date. For example, vidv = 1, razdel = 20370, sroks = 04/01/2016 and vidv = 1, razdel = 3030, sroks = 04/01/2017, the second example will be relevant here, since it has a later date. I solved this half of the problem with the above code.
But there is one more condition. If the value of the variable is equal to the current razdel, select ALL of the actual data and hide the non-relevant. If osn = 3030, then select lines 12 and 13. If osn = 60090, then select lines 12 and 13.
If the value of the variable is not the current razdel, do not select anything. If osn = 20370, then select nothing, since there is a line with the current razdel = '3030', vidv = '1' and later date than razdel = '20370', in this case razdel = '20370' is not relevant.
