0

I have the following GlobalTax table below and I need to sort by TaxCode but with a particular sort order. The first set of items should be the ones which first character of Type column = 'F', then 'S' and finally 'L'

enter image description here

I'm able to sort by type like this:

select TaxCode,
   Type,
    CASE WHEN LEFT(gt.Type, 1) = 'F' THEN 1
         WHEN LEFT(gt.Type, 1) = 'S' THEN 2
         WHEN LEFT(gt.Type, 1) = 'L' THEN 3
    ELSE 4
    END as SortOrder
from GlobalTax gt
order by sortorder

Which returns:

enter image description here

However, it's not sorting each set Alphabetically by TaxCode. What am I missing?

Here is a fiddle: http://rextester.com/JGLNP57037

0

1 Answer 1

2

Simply add taxcode to order by:

select TaxCode,
   Type,
    CASE WHEN LEFT(gt.Type, 1) = 'F' THEN 1
         WHEN LEFT(gt.Type, 1) = 'S' THEN 2
         WHEN LEFT(gt.Type, 1) = 'L' THEN 3
    ELSE 4
    END as SortOrder
from GlobalTax gt
order by sortorder, taxcode

You can also simlify the case expression:

select TaxCode,
   Type,
    CASE LEFT(gt.Type, 1)
         WHEN 'F' THEN 1
         WHEN 'S' THEN 2
         WHEN 'L' THEN 3
    ELSE 4
    END as SortOrder
from GlobalTax gt
order by sortorder, taxcode
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.