Logic SELECT CASE WHEN
I would like help in building the following logic:
I have my main table and two other tables A and B, which have foreign key of main.
When a column X is filled in the table I need to classify my information as being of " Type 1" When there is any field in Table B being B. foreign ID = P. id_principal. I need to classify my information as being of "Type 2"
But, in field X of table a there are some filled only with comma',' in these cases, even when I have filled with comma and there is nothing in Table B then my information is still "Type 1"
And if it is filled only with comma', 'and there is record in Table B then it will be only of"Type 2"
And finally when column x of Table A is filled and there is record in Table B then it is information of "Type 1 and type 2"
As you can see in this example the IDS 1 and 3 of the main table should be classified as Type 1
ID 6 should only be of type 2
And the other IDs being like Type 1 and two
With the following query
select
(
CASE WHEN (A.de_inf is not null or A.de_inf != '') and A.de_inf != ','
AND EXISTS (select tit_inf from B where tit_inf IS NOT NULL OR tit_inf != '')
THEN 'Tipo 1 e Tipo 2'
ELSE
CASE WHEN A.de_inf = ',' or (A.de_inf is not null or A.de_inf != '')
AND NOT EXISTS (select tit_inf from B where tit_inf IS NOT NULL OR tit_inf != ''
)
THEN 'Tipo 1'
ELSE
CASE WHEN A.de_inf = ','
AND EXISTS (select tit_inf from B where tit_inf IS NOT NULL OR tit_inf != '')
THEN 'Tipo 2'
end
end
end
) as tipo
from
principal as p
left join A on p.id_inf = A.id_inf
I got this result
Or also this shape:
SELECT
p.id_inf,
(
CASE WHEN A.de_inf != ',' THEN
CASE WHEN A.de_inf is not null or A.de_inf != '' THEN
CASE WHEN EXISTS (select tit_inf from B where tit_inf IS NOT NULL OR tit_inf != '')
THEN 'Tipo 1 e 2' ELSE 'Tipo 1'
END
end
else
'Tipo 2'
END
) AS tipo
from
principal as p
left join A on p.id_inf = A.id_inf
1 answers
I don't know if it's what exactly you want but the query below comes to the result you expected:
SELECT (
CASE WHEN (A.de_inf is not null or A.de_inf != '')
AND A.de_inf != ','
AND EXISTS (select tit_inf from B where tit_inf IS NOT NULL OR tit_inf != '')
THEN 'Tipo 1 e Tipo 2'
ELSE
CASE WHEN A.de_inf = ',' AND (A.de_inf is not null or A.de_inf != '')
AND NOT EXISTS (select tit_inf from B where B.ID_inf = A.ID_INF
)
THEN 'Tipo 1'
ELSE
CASE WHEN A.de_inf = ','
AND EXISTS (select tit_inf from B where tit_inf != '')
THEN 'Tipo 2'
end
end
end
) as tipo,A.ID_INF
from
principal as p
left join A on p.id_inf = A.id_inf