2016-12-01 54 views
0

我有下面的GlobalTax表格,我需要按TaxCode排序,但具有特定的排序順序。第一組項目的應該是那些這類型列=「F」,然後「S」最後「L」有條件的多列數據庫排序

enter image description here

我能夠按類型這樣排序的第一個字符:

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 

將返回:

enter image description here

然而,這不是每個排序由TaxCode設置按字母順序。 我錯過了什麼?

這裏是一個小提琴:http://rextester.com/JGLNP57037

回答

2

只需添加taxcode訂購方式:

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 

您也可以simlify的case表達:

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