For my example, I need to do a **procedure** that calculates the balance on the **desired date** for the **selected batch**.

If there is **no balance for the date entered**, **it finds and calculates the balance for the last existing date**.

I have tried something like this:

```
select saldo_do, saldo_br
from
trr_extracts
where batch = 135 and dat_extr = '21.3.2019';

```

Also tried:

```
SELECT dat_extr, max(dat_extr)
from trr_extracts
where batch = 135
group by dat_extr;

SELECT IFNULL(dat_extr('21.3.2023'), max(dat_extr)
FROM trr_extracts;

```

The problem is, **how to write a statement which returns only one of parameters (saldo\_do or saldo\_br) and finds the last date from batch that is given**.

**EXPLANATION:**

The **saldo\_do** is (positive account balance currency) while **saldo\_br** is (negative account balance currency). The account can only have one. (it can be in plus or in minus with currency balance).

**If I run this code:**

```
select saldo_do, saldo_br
from
trr_extracts
where batch = 135 and dat_extr = '21.3.2019';

```

**The result is:**

[![enter image description here](https://i.stack.imgur.com/Akf67.png)](https://i.stack.imgur.com/Akf67.png)

This account has positive balance. Because of positive balance it should just print saldo\_do WITHOUT saldo\_br. Like this.

[![enter image description here](https://i.stack.imgur.com/Ns5TC.png)](https://i.stack.imgur.com/Ns5TC.png)

**If negative**, then It should only print saldo\_br.

**For now**, I want to print only one result. **Positive** if the account is in positive. **Negative** if account is negative.

**THE NEXT PROBLEM IS:**

if the entered date in the example above ('21.3.2019') **DOES NOT EXIST** for the **given batch of (135)**, the statement then **should find the LAST date of batch 135** and use that date insted.