ORDER BY + IN 语句?

ORDER BY + IN statement?

The marketing department wants to focus on the customers from Noth America first. Get the ID, last name and country of all customers. Build the list by bringing up the customers living in Canada and in the USA first, and finally order them by ID. Tip: use the IN expression in the ORDER BY clause.

我试过很多次了

SELECT CustomerID, LastName, Country
FROM Customer
ORDER BY Country IN ('Canada', 'USA'), CustomerID

但它似乎不起作用,因为它按照它们在原始 table(也按 ID 排序)中出现的顺序从所有客户那里获取指定字段,即使我删除了 CustomerID 来自 ORDER BY 子句,而不关心它们属于哪个国家。

我该怎么办?我是 SQL 的新手,不知道如何解决这个问题。

编辑:WHERE 根本不适合table,因为我需要考虑 所有 客户,只确保加拿大和美国的出现在列表的顶部。 此外,我不确定像 UNIONASEXCEPT 之类的语句是否应该使用,因为本教程还没有那么深入。

IN 表达式没有 return 值所以你不能排序

你可以试试:

SELECT CustomerID, LastName, Country
FROM Customer
WHERE Country='Canada'

UNION ALL

SELECT CustomerID, LastName, Country
FROM Customer
WHERE Country='USA'
ORDER BY CustomerID

Using ORDER BY with UNION, EXCEPT, and INTERSECT When a query uses the UNION, EXCEPT, or INTERSECT operators, the ORDER BY clause must be specified at the end of the statement and the results of the combined queries are sorted. The following example returns all products that are red or yellow and sorts this combined list by the column ListPrice. https://msdn.microsoft.com/en-us/library/ms188385.aspx#Union

并非每个 DBMS 都有布尔数据类型。所以

的结果
Country IN ('Canada', 'USA'), 

这是一个布尔值,无法在这些 DBMS 中进行排序。

但是,您可以使用 CASE 表达式来赋值:

SELECT CustomerID, LastName, Country
FROM Customer
ORDER BY CASE WHEN Country IN ('Canada', 'USA') THEN 1 ELSE 2 END, CustomerID;

SELECT 客户 ID、姓氏、国家/地区 来自客户 按国家排序 IN ('Canada', 'USA') desc, CustomerID asc