我从表中得到以下数据:
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
有什么建议吗?
答案 0 :(得分:2)
就像
一样简单SELECT ID, Name, IsFeatured
FROM table1
ORDER BY IsFeatured DESC, Name
答案 1 :(得分:2)
不需要使用Union。只需按“是”,“否”和“按名称”排序 如果您只有Yes或No作为值,那么按降序排序应该可以做到。
SELECT
ID,
[Name],
IsFeatured
FROM table1
ORDER BY IsFeatured desc,[Name]
答案 2 :(得分:1)
使用ORDER BY
以特定顺序获取行:
SELECT ID, Name, IsFeatured
FROM table1
ORDER BY (CASE WHEN IsFeatured = 'Yes' THEN 1 ELSE 2 END),
Name;
SQL表和结果集表示无序集。除了最外层ORDER BY
中SELECT
的查询创建的结果集外,这是正确的。