Union 实现自定义分组

本文介绍了一种使用SQL查询特定条件记录的方法,通过联合查询确保特定条件的记录优先显示,并按照指定方式排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    如题:选择所有classnumber =1或rating =9的记录,使得classnumber =1且rating =9的记录排在最前面,并且classnumber =1且rating =9的记录按id降序排列。

 

下面是我模仿的例子:

create table myCreateTBPractice
(

     Iname nvarchar(50) not null,

     classnumber int not null,

     studentid int primary key ,

     rating int Null

)
注意:创建表的时候用的是()而不是{} 其次字段之间用‘,’而不用‘;’ 可空的用null;

 

我们采用关键字Union

    select * from [myCreateTBPractice] where classnumber = '1' and rating = '9' (1) union all
 select * from [myCreateTBPractice] where classnumber = '1' and rating != '9' union all
  select * from [myCreateTBPractice] where rating = '9' and classnumber != '1'  order by studentID desc

 

注意:黑体字部分不能放在位置(1),要放在末尾。

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值