Using Case in Order By with Union

Asked

Viewed 348 times

0

I’m having trouble using Order by com Case on Union, so it works:

select tb_a.nr_rua, tb_a.cod_altura, tb_a.cod_posicao, tb_a.cod_lado where ......
union all
select tb_b.nr_rua, tb_b.cod_altura, tb_b.cod_posicao, tb_b.cod_lado where ......
order by
2,3,1

Now if I do so, using the case:

order by 2,
 (case when 4 = 'M' then 3 END) DESC,
 (case when 4 <> 'M' then 3 END),
1

Or:

order by 2,
 (case when cod_lado = 'M' then cod_posicao END) DESC,
 (case when cod_lado <> 'M' then cod_posicao END),
1

Or:

order by 2,
 (case when cod_lado = 'M' then 3 END) DESC,
 (case when cod_lado <> 'M' then 3 END),
1

Also not working. following Error:

Invalid token.
Dynamic SQL Error.
SQL error code = -104.
Invalid command.
invalid ORDER BY clause.

I’m using the Firebird.

  • If used within select, please check the Firebird https://firebirdsql.org/refdocs/langrefupd15-case.htmldocumentation

  • Right @Everson in my case, which I would have to use to solve my problem?

  • select tb_a.nr_rua, tb_a.cod_altura, tb_a.cod_posicao, &#xA; case &#xA; when cod_lado = 'M' then 3&#xA; when cod_lado <> 'M' then 4 &#xA; end as cod_lado&#xA;where ..... &#xA;union all&#xA;select tb_b.nr_rua, tb_b.cod_altura, tb_b.cod_posicao,&#xA; case &#xA; when cod_lado = 'M' then 3&#xA; when cod_lado <> 'M' then 4 &#xA; end as cod_lado where ......&#xA;order by cod_lado

1 answer

1

Your order by should provide an expression that can be evaluated for each record. When you use:

(case when cod_lado = 'M' then cod_posicao END) DESC,

Expression result missing for records cod_lado <> 'M'.

Maybe you can use something like this:

if(cod_lado = 'M', 0, 1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.