sql server自定义排序(还有mysql)
2023-09-11 14:21:09 时间
【1】sql server自定义排序
1. c2列的数据按'4','1','2'的指定顺序排序
(1) 使用union
select * from t_orderby where c2='4' union all select * from t_orderby where c2='1' union all select * from t_orderby where c2='2'
(2) charindex
select * from t_orderby order by charindex(c2,'4,1,2')
(3) case when
select * from t_orderby order by case when c2='4' then 1 when c2='1' then 2 when c2='2' then 3 end,c1 desc
2. 随机排序
(1) 要求c2='4'排第一行,其他的行随机排序
select * from t_orderby order by case when c2='4' then 1 else 1+rand() end
(2) 所有行随机排序
select * from t_orderby order by newid()
(3) 随机取出第一行
select top 1 * from t_orderby order by newid()
3. 要求列c3中数据,先按第一个字符排序,再按第二个字符排序
select * from t_orderby order by left(c3,1),ASCII(substring(c3,2,1))
【2】mysql自定义排序
问题描述 大家都知道, MySQL 中按某字段升序排列的 SQL 为 (以 id 为例, 下同): SELECT * FROM `MyTable` WHERE `id` IN (1, 7, 3, 5) ORDER BY `id` ASC 降序排列的 SQL 为: SELECT * FROM `MyTable` WHERE `id` IN (1, 7, 3, 5) ORDER BY `id` DESC 有时以上排序并不能满足我们的需求. 例如, 我们想要按 id 以 5, 3, 7, 1 的顺序排列, 该如何实现. 这也是很多国内外同行经常遇到的问题之一. 下面我们给出按表中某字段, 以我们想要的列表方式排序的解决方案. 解决方案 用"按字段排序" (ORDER BY FIELD). 语法 ORDER BY FIELD(`id`, 5, 3, 7, 1) 要注意的是, FIELD 后面是没有空格的. 因此, 完整的 SQL 为: SELECT * FROM `MyTable` WHERE `id` IN (1, 7, 3, 5) ORDER BY FIELD(`id`, 5, 3, 7, 1) 常见应用 SELECT * FROM `MyTable` WHERE `name` IN ('张三', '李四', '王五', '孙六') ORDER BY FIELD(`name`, '李四', '孙六', '张三', '王五')
参考资料
相关文章
- 第 10 章 MySQL Server 性能优化
- 【mysql+pandas】用MySQL命令处理在python中处理DataFrame数据 pandasql库
- 报错:MySQL Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'
- 数据库表设计时一对一关系存在的必要性 数据库一对一、一对多、多对多设计 面试逻辑题3.31 sql server 查询某个表被哪些存储过程调用 DataTable根据字段去重 .Net Core Cors中间件解析 分析MySQL中哪些情况下数据库索引会失效
- 用navicat连接数据库报错:1130-host ... is not allowed to connect to this MySql server如何处理
- 【MySQL高级】MySql中常用工具及Mysql 日志
- mysql错误:java.sql.SQLException: The server time zone value ‘xxx‘ is unrecognized or represents 解决方法
- 【MySQL进阶-06】深入理解mysql的内核查询成本计算
- MySQL root修改普通用户密码及Mysql 修改root密码
- 【mysql问题】解决2003-Can‘t connect to MySQL server on ‘ ‘(10060“Unknown error“)
- SQL Server 数据导入Mysql详细教程
- MYSQL导入csv类型的数据出现The MySQL server is running with the --secure-file-priv option
- sql: MySQL and Microsoft SQL Server Stored Procedures IN, OUT using csharp code
- 有关Mysql的mysql_store_result函数返回NULL的情况以及其他注意事项
- iBatis自动生成的主键 (Oracle,MS Sql Server,MySQL)【转】
- PostgreSQL通过mysql_fdw访问MySQL数据库
- (4.61)sql server执行SQL遇到错误不中断
- (4.52)解决sql server动态SQL中对表字段操作时需要频繁 ISNULL的问题
- 【3.3】mysql链接服务器,Federated存储引擎实现远程表,相当于sql server的连接服务器
- Oracle、SQL Server、MySQL数据类型对比