I want to make a select, with 3 columns, the first is an id , the second is a name , and the third another name .
The objective is to obtain in a final table that I already have mounted, a column that contains one or another name depending on whether they have something or not for that id defined.
Pseudocode:
select id,
if(nombre1 is not null) entonces obtengo nombre1
else if (nombre2 is not null) entonces obtengo nombre2
else ''
I have seen examples with conditions CASE WHEN
and EXISTS
, but I do not give with it. The first name I get with this query:
select [AM].[idAM], (select top 1 Responsable) GestorAM from [RegModifNRAM]
inner join [AM]
on [AM].[idAM] = [RegModifNRAM].[idAM]
inner join [AccionesRegModifCulture]
on AccionesRegModifCulture.idAccionesRegModif = [RegModifNRAM].[idAccion] and AccionesRegModifCulture.idCulture = 1
INNER JOIN Auditoria
ON [RegModifNRAM].idAuditoria = Auditoria.idAuditoria
where [RegModifNRAM].[idAccion] in (50000,50023,50024,50026,50028,50030,50031,50036,50038,50039,50041,50044)
order by [RegModifNRAM].[fx_Creacion] desc
... and the second name like this:
Select am.idam,
( SELECT TOP 1 LTRIM(RTRIM(ISNULL(dbo.Responsable.apellido1, '')
+ ' '
+ ISNULL(dbo.Responsable.apellido2, '')
+ ' '
+ ISNULL(dbo.Responsable.nombre, '')))
FROM ResponsableAMPrivilegio
LEFT JOIN Responsable
ON Responsable.idResponsable = ResponsableAMPrivilegio.idResponsable
WHERE (ResponsableAMPrivilegio.borrado = 0 OR ResponsableAMPrivilegio.borrado IS NULL)
AND ResponsableAMPrivilegio.idPrivilegio = 40 --P40 GESTOR SAM
and am.idam = ResponsableAMPrivilegio.idaccionmejora
AND ResponsableAMPrivilegio.idAccionMejora in (SELECT ID FROM #IDSENTIDADESeq)
) as 'GestorAM'
from AM
WHERE AM.idAM in (SELECT ID FROM #IDSENTIDADESeq)
I see if I can get a name in the first query, if I can not, I see in the second, but if not, I leave ''
.
I've been looking at subqueries within conditions CASE
, and within IF..ELSE
to try to get it, but I do not get it.
I give the example of the two tables and what I want to achieve:
First table:
idAM Responsable
5982 RAUL CORBELLA CARRASCO
6854 PEDRO JIMÉNEZ MARTÍN
8555 NULL
8556 NULL
Second table:
idAM Responsable
5982 NULL
6854 PEDRO JIMÉNEZ MARTÍN
8555 MARTÍN CEBALLOS
8556 NULL
In this way, the result in the final table would be something like this:
idAM Columna1 ... ... Responsable ... ...
5982 ... RAUL CORBELLA CARRASCO
6854 ... PEDRO JIMÉNEZ MARTÍN
8555 ... MARTÍN CEBALLOS
8556 ... NULL