带有IN表达式的ORDER BY

时间:2018-06-02 14:13:57

标签: tsql

我想通过CustomerID订购,也想订购ORDER BY 2国家/地区,

我有

SELECT CustomerID, Country
FROM Customer
ORDER BY Country IN ("USA", "CANADA") ASC
ORDER BY Customer ID ASC;

应该返回

4, Canada
7, USA
8, USA
11, USA
12, Brazil
13, Belgium

1 个答案:

答案 0 :(得分:1)

CASE子句中使用ORDER BY表达式:

SELECT CustomerID, Country
FROM Customer
ORDER BY
    CASE WHEN Country IN ("USA", "CANADA") THEN 0 ELSE 1 END,
    CustomerID;

这将首先将所有客户置于美国或加拿大,其次是来自所有其他国家/地区的客户。在这两组中的每一组中,记录将按CustomerID升序排序。