How to order by an arbitrary condition in SQL(如何按 SQL 中的任意条件排序)
本文介绍了如何按 SQL 中的任意条件排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下表:
CREATE TABLE Bable(id int 身份主键,名称 varchar(20),关于 varchar(30));INSERT INTO Bable (name,about) VALUES('ООО Name Firm 1','texttexttexttext'),('ООО Name Firm 2','texttexttexttext'),('ООО Name Firm 3','texttexttexttext'),('ООО Name Firm 4','texttexttexttext'),('ООО Name Firm 5','texttexttexttext'),('ООО Name Firm $1','texttexttexttext'),('ООО Name Firm $2','texttexttexttext'),('ООО Name Firm $3','texttexttexttext'),('ООО Name Firm 6','texttexttexttext'),('ООО Name Firm 7','texttexttexttext')
我可以编写如下查询:
SELECT * FROM Bable WHERE about = 'texttexttexttext'
如何更改此查询以返回排序的结果,使得名称包含$"的那些首先出现,然后是那些不出现的,然后每个组按 name
升序排列?>
表格结构在这里
解决方案
SELECT *从 BableORDER BY CASE WHEN name LIKE '%$..' THEN 0 ELSE 1 END,姓名
- SQLFiddle 演示
I have the following table:
CREATE TABLE Bable
(
id int identity primary key,
name varchar(20),
about varchar(30)
);
INSERT INTO Bable (name,about) VALUES
('ООО Name Firm 1','texttexttexttext'),
('ООО Name Firm 2','texttexttexttext'),
('ООО Name Firm 3','texttexttexttext'),
('ООО Name Firm 4','texttexttexttext'),
('ООО Name Firm 5','texttexttexttext'),
('ООО Name Firm $1','texttexttexttext'),
('ООО Name Firm $2','texttexttexttext'),
('ООО Name Firm $3','texttexttexttext'),
('ООО Name Firm 6','texttexttexttext'),
('ООО Name Firm 7','texttexttexttext')
And I can write a query like the following:
SELECT * FROM Bable WHERE about = 'texttexttexttext'
How can I alter this query to return results ordered such that those with names containing "$" appear first, followed by those that do not, with each group then ordered by name
ascending?
Structure of the table is here
解决方案
SELECT *
FROM Bable
ORDER BY CASE WHEN name LIKE '%$..' THEN 0 ELSE 1 END,
Name
- SQLFiddle Demo
这篇关于如何按 SQL 中的任意条件排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何按 SQL 中的任意条件排序


猜你喜欢
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01