Problem with Order By Case Over 9 When

Asked

Viewed 25 times

0

How to correctly use ORDER BY CASE WHEN with more than 9 records ?

In the example below I am using a case when with more than 9 records and when it arrives at position 10 , 11 ,12 e 13 the order is wrong.

What is the correct way to use in this case ?

ORDER BY CASE descricao
WHEN 'Rec. Op. Liquida' THEN 0
WHEN 'VENDA MERCADORIA' THEN 1
WHEN 'ICMS S.T S/ VENDA' THEN 2
WHEN 'DEVOLUÇÃO DE VENDA' THEN 3
WHEN 'VENDA LÍQUIDA' THEN 4
WHEN 'ICMS' THEN 5
WHEN 'ICMS ST' THEN 6
WHEN 'TOTAL ICMS' THEN 7
WHEN 'PIS' THEN 8
WHEN 'COFINS' THEN 9
WHEN 'TOTAL PIS/COFINS' THEN 10
WHEN 'DEV X FAT' THEN 11
WHEN 'BONF X FAT' THEN 12
WHEN 'BONIFICAÇÃO' THEN 13
ELSE descricao END;

In this image is the result and side the position of the element in the result.

inserir a descrição da imagem aqui

Example in Sqlfiddle Sqlfiddle, I couldn’t get it right why I use many variables and multiple querys, if anyone can adjust to the example look better thanks, but the result can be seen in the image.

1 answer

0

It worked using this way, I used two characters and put quotes

ORDER BY CASE descricao
WHEN 'Rec. Op. Liquida' THEN '01'
WHEN 'VENDA MERCADORIA' THEN '02'
WHEN 'ICMS S.T S/ VENDA' THEN '03'
WHEN 'DEVOLUÇÃO DE VENDA' THEN '04'
WHEN 'VENDA LÍQUIDA' THEN '05'
WHEN 'ICMS' THEN '06'
WHEN 'ICMS ST' THEN '07'
WHEN 'TOTAL ICMS' THEN '08'
WHEN 'PIS' THEN '09'
WHEN 'COFINS' THEN '10'
WHEN 'TOTAL PIS/COFINS' THEN '11'
WHEN 'DEV X FAT' THEN '12'
WHEN 'BONF X FAT' THEN '13'
WHEN 'BONIFICAÇÃO' THEN '14'
ELSE descricao END;

Browser other questions tagged

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