jeudi 17 mai 2018

Error in Conditional UNION

I have this SQL:

SELECT        MONTH(data) AS MES, cor, CASE month(data) 
                          WHEN 1 THEN 'Janeiro' WHEN 2 THEN 'Fevereiro' WHEN 3 THEN 'Março' WHEN 4 THEN 'Abril' WHEN 5 THEN 'Maio' WHEN 6 THEN 'Junho' WHEN 7 THEN 'Julho' WHEN
                          8 THEN 'Agosto' WHEN 9 THEN 'Setembro' WHEN 10 THEN 'Outubro' WHEN 11 THEN 'Novembro' WHEN 12 THEN 'Dezembro' END AS MESCOR, COUNT(*) 
                          AS Expr1, CASE cor WHEN 'AM' THEN '2' WHEN 'VD' THEN '1' WHEN 'VM' THEN '3' END AS Expr2 

FROM            TBINICIATIVAS_PREVISTAS
WHERE        (login ='xxxxxxx')
GROUP BY MONTH(data), cor

UNION 
SELECT '1', 'VD', 'Janeiro',0,'1' 

UNION
SELECT '1', 'AM', 'Janeiro',0,'2' 

UNION
SELECT '1', 'VM', 'Janeiro',0,'3'


ORDER BY expr2, mes


But I need the UNION to be conditional. Something like:

if (select count(*) .... where cond1...) = 0
UNION 
SELECT '1', 'VD', 'Janeiro',0,'1' 

if (select  count(*) ....where cond2...) = 0
UNION
SELECT '1', 'AM', 'Janeiro',0,'2'

if (select  count(*) ....where cond3...) = 0
UNION
SELECT '1', 'VM', 'Janeiro',0,'3'

I tryed, but I always got a sintax error. Is it possible to do that?

Aucun commentaire:

Enregistrer un commentaire