SQL 自定义顺序按子句

编程入门 行业动态 更新时间:2024-10-23 03:19:39
本文介绍了SQL 自定义顺序按子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

一个简单的问题.我有一个查询带回 2 列描述"和金额"在描述中,我们有 3 个结果.

A quick Question. I have a query that brings back 2 columns 'Description' and 'Amount' In the Description we have 3 outcomes.

'黄金 - 拥有'、'青铜 - 无地'和'白银 - 确定/提供'

'Gold - owned', 'Bronze - no land' and 'Silver - identified / offered'

我希望结果按以下顺序显示金、银、铜

I would like the result to show in an order of Gold,Silver,Bronze

Order By Asc 或 Desc 不能实现这一点.有没有办法自定义 Order by 子句?

Order By Asc or Desc does not achieve this. Is there a way to customize a Order by clause?

对此有任何帮助将不胜感激,谢谢生锈了

Any Help on this Would be appreciated thanks Rusty

推荐答案

在 CASE 内部,您可以为每个分配一个数值并按升序排列.如果您需要查询大表,请考虑在 Description 上添加索引以提高排序性能.

Inside of a CASE, you may ascribe a numeric value to each and order those ascending. If you will need to query a large table, consider adding an index on Description to improve sorting performance.

ORDER BY CASE WHEN Description = 'Gold - owned' THEN 0 WHEN Description = 'Silver - identified / offered' THEN 1 WHEN Description = 'Bronze - no land' THEN 2 ELSE 99 /* Any other value (which you should not have) sorts after all */ END ASC /* And don't forget to be explicit about ASC order though it's the default */

由于这与 ORDER BY 中的普通列一样工作,如果您需要按 Amount 或其他列排序,可以附加逗号.

Since this works like a normal column in the ORDER BY, if you needed to then sort by the Amount or other column, it can be appended with a comma.

ORDER BY CASE WHEN Description = 'Gold '... END ASC, Amount DESC, AnotherColumn ASC

更多推荐

SQL 自定义顺序按子句

本文发布于:2023-10-23 22:48:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522231.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子句   自定义   顺序   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!