首先使用 JOIN/UNION 显示特色记录

Display Featured Records First Using JOIN/UNION

我有来自 table 的以下数据:

ID  Name        IsFeatured
1   Alpha       Yes
2   Echo        No
3   Delta       Yes
4   Charlie     Yes
5   Bravo       No

我想先显示特色记录,按(名称)升序排序:

ID  Name        IsFeatured
1   Alpha       Yes
4   Charlie     Yes
3   Delta       Yes
5   Bravo       No
2   Echo        No

我使用以下查询来合并两个单独的查询,但它不允许我使用 ORDER BY 两次。

SELECT ID, Name, IsFeatured FROM table1 WHERE IsFeatured='Yes' ORDER BY Name
UNION ALL
SELECT ID, Name, IsFeatured FROM table1 WHERE IsFeatured='No' ORDER BY Name

有什么建议吗?

使用ORDER BY获取特定顺序的行:

SELECT ID, Name, IsFeatured
FROM table1 
ORDER BY (CASE WHEN IsFeatured = 'Yes' THEN 1 ELSE 2 END),
         Name;

SQL 表和结果集表示 无序 集。除了由最外层 SELECT.

中具有 ORDER BY 的查询创建的结果集外,这是正确的

就像

一样简单
SELECT ID, Name, IsFeatured 
FROM table1
ORDER BY IsFeatured DESC, Name

不需要使用联盟。只需按“是”、“否”和“名称”排序。
如果您只有 Yes 或 No 作为值,那么按降序排序应该可以解决问题。

SELECT
  ID,
  [Name],
  IsFeatured
FROM table1
ORDER BY IsFeatured desc,[Name]