I have been presented with a case that I do not know how to solve, I am trying to filter certain data from several tables, in this case I will only put a sample of the use case that I do not know how to solve.
Table ESTATUSEMPLEADO
: (It has many more fields, it is just a sample)
╔══════════╦═══════╦══════╗
║ Codigo ║ Nombre║ .... ║
╠══════════╬═══════╬══════╣
║ 1 ║ Juan ║ .... ║
║ 2 ║ José ║ .... ║
║ 3 ║ Maria ║ .... ║
║ 4 ║ Joel ║ .... ║
║ 5 ║ Ramón ║ .... ║
║ 6 ║ Teresa║ .... ║
║ .... ║ .... ║ .... ║
╚══════════╩═══════╩══════╝
Table NOTIFICACION
: (In this the field Codigo
can be repeated, it is a Details table...)
╔══════════╦═══════╦═══════╦════════════╗
║ Codigo ║ Estado║ UserN ║ OtroCampo ║
╠══════════╬═══════╬═══════╬════════════╣
║ 4 ║ N ║ admin ║ Dato1 ║
║ 1 ║ S ║ admin ║ Dato2 ║
║ 6 ║ N ║ admin ║ Dato3 ║
║ 1 ║ N ║ otro ║ Dato4 ║
╚══════════╩═══════╩═══════╩════════════╝
SELECT e.Codigo, e.Nombre,
Leida = case when n.Estado = 'S' then 'S' else 'N' end,
n.OtroCampo,
FROM ESTATUSEMPLEADO e
LEFT JOIN NOTIFICACION n
ON e.Codigo = n.Codigo AND n.UserN = 'admin' AND n.Estado in('N')
WHERE e.AlgunCampo = ....
Desired result:
╔══════════╦═════════╦═══════╦════════════╗
║ Codigo ║ Nombre ║ Leida ║ OtroCampo ║
╠══════════╬═════════╬═══════╬════════════╣
║ 2 ║ José ║ N ║ NULL ║
║ 3 ║ Maria ║ N ║ NULL ║
║ 4 ║ Joel ║ N ║ Dato1 ║
║ 5 ║ Ramón ║ N ║ NULL ║
║ 6 ║ Teresa ║ N ║ Dato3 ║
╚══════════╩═════════╩═══════╩════════════╝
With this select it is showing me all the data of the table ESTATUSEMPLEADO
the filter UserN
works correctly, when I also want to filter by Estado
it does not filter the data correctly, it must exclude Codigo = 1
me since I am filtering that Estado = 'N'
instead it is showing it to me in the result and shows the field Leida = 'N'
.
I am not using WHERE to filter the table
NOTIFICACION
because this table may or may not contain records, and if I do it in the Where, it will only show me the data that is in this table.WHERE e.SomeField = .... (This is because I also have some conditions but they belong to the table
ESTATUSEMPLEADO
)I use
n.Estado in('N')
since there are times when I have to filter theS
andN
.
I want to get all the data from the table ESTATUSEMPLEADO
and do the left join with the table NOTIFICACION
, to filter the data and only show me the data that meets the specified conditions.
Environment: SQL Server 2008 R2
If my question is not entirely clear, please ask questions in the comments. Thanks.
Something like that:
We take the status filter to
where
and consider the eventualNULL
ones due to non-existence of rows inNOTIFICACION
asN
To deal with comparisons of the set on the right you can explicitly implement that the field is null.