From what I understand you would have a box table similar to this:
| COD_FILIAL | TIPO | DATA |
|------------|------|----------|
| 1 | 00 | 20160101 |
| 1 | 99 | 20160101 |
| 2 | 00 | 20160101 |
| 2 | 99 | 20160101 |
| 3 | 00 | 20160101 |
| 1 | 00 | 20160102 |
| 1 | 99 | 20160102 |
| 2 | 00 | 20160102 |
| 1 | 00 | 20160103 |
And you expect the following results (affiliates where there was box opening on a given day but had no closure):
| COD_FILIAL | TIPO | DATA |
|------------|------|----------|
| 3 | 00 | 20160101 |
| 2 | 00 | 20160102 |
| 1 | 00 | 20160103 |
Considering that there should always be a box opening to have a closure, think that the boxes without closure are the difference of the subset of the closed boxes (the part highlighted in gray):
To get only the gray part, think that you have two lists: affiliates and days with open box and affiliates with closed box. By joining these lists, take out the part that intersects and you will have the days that the boxes have been open.
SELECT *
FROM (SELECT * FROM CAIXA WHERE STATUS = '00') AS abertura
LEFT JOIN (SELECT * FROM CAIXA WHERE STATUS = '99') AS fechamento ON
abertura.cod_filial = fechamento.cod_filial AND
abertura.data = fechamento.data
WHERE fechamento.status IS NULL;
See the query running on SQL Fiddle.
To do this query I used the concepts of subquery and joins. This query can be done in different ways using a SQL Server CVE.
I leave below some links that can help you better understand these concepts.
You can place the complete structure of the tables(s)?
– bruno
These fields are no longer enough?
– gmsantos