SQL Server 指定字段自定义排序的实现

本文主要介绍两种用于实现自定义排序的方法,两种方法都是基于order by来实现的。

构建测试销售表sales:

# 创建销售表sales:
create table sales(
year    int,
country varchar(20),
product varchar(32),
profit  int
)
 
# 向销售表sales中插入数据:
insert into sales values(2000,'USA','Calculator',105),
insert into sales values(2000,'USA','Computer',1500),
insert into sales values(2001,'USA','Calculator',50),
insert into sales values(2001,'USA','Computer',2500),
insert into sales values(2001,'USA','Computer',1200),
insert into sales values(2001,'USA','TV',150),
insert into sales values(2001,'USA','TV',100),
insert into sales values(2000,'Finland','Computer',1500),
insert into sales values(2000,'Finland','Phone',100),
insert into sales values(2001,'Finland','Phone',2500),
insert into sales values(2000,'India','Calculator',150),
insert into sales values(2000,'India','Calculator',75),
insert into sales values(2000,'India','Computer',1200)
insert into sales values(2001,'India','Calculator',100);

查询需求:从销售表sales中查询出不同年份下销售产品在各国中的销售情况(包括销售的产品种类和销售利润),并将国家按照Finland,USA,India这种顺序排列。

方法一:利用order by+case when

SQL代码1:

select year,country,product,profit from sales
order by year,case when country='USA' then 1 when country='India' then 2 end

查询结果:

 

 为便于理解SQL代码1中的代码,可以对其稍作修改得到SQL代码2:

select year,country,case when country='USA' then 1 when country='India' then 2 end as
country_number,product,profit from sales
order by year,country_number

我们知道当case when中when后面的条件没有匹配成功时,case when返回的是else后面的值,若else语句也没有,则case when返回NULL。而由上述查询结果我们可以看到利用order by进行排序时,NULL值是排在非NULL值前面的。

方法一:利用order by+charindex

SQL代码3:

select year,country,product,profit from sales
order by year,charindex(country,'Finland,USA,India')

 查询结果:

为便于理解order by+charindex如何实现自定义排序,对SQL代码3稍作修改得到SQL代码4:

select year,country,charindex(country,'Finland,USA,India') as country_number,product,profit from sales 
order by year,country_number

 查询结果:

从上面最近的查询结果我们可以看到,charindex()的计算结果可以当成一个新的字段,而order by +charindex()就等价于 order by +charindex()的返回结果字段。

PS:关于MySQL中的自定义排序可以参考  https://blog.csdn.net/qq_41080850/article/details/85056595

 

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值