sql 分组排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 分组排序相关的知识,希望对你有一定的参考价值。

一个表内三个字段,如:
id check_id idate
1 1 12-2
2 3 12-1
3 2 12-3
4 3 12-3
5 2 12-1
6 1 12-1
7 4 12-2
8 3 12-2
想查询出来的结果先按check_id=4 and check_id=2的在前且按idate排序,然后后面是其它的。记录集如下:
id check_id idate
7 4 12-2
5 2 12-1
3 2 12-3
6 1 12-1
1 1 12-2
2 3 12-1
8 3 12-2
4 3 12-3
求一个sql语句实现,不胜感激!谢谢
谢谢try的回答,问题是我想把这个用在ASP里的一个很小的地方进行查询, 这样写是不是太麻烦了,还有更好的方法吗?期待中

参考技术A 没有计算机理解的顺序,必需构造一个表示顺序的函数。完整的实现语句如下:

select *,
case check_id
when 4 then 1
when 2 then 2
else check_id*10
end as def_order
from 表 order by def_order,idate

这里用CASE函数定义一个新的顺序,如果check_id=4,新的排序号为1;如果check_id=2,新的排序号为2;如果check_id为其它,新的排序号为check_id*10,这样能满足要求的顺序。

楼上的兄弟的解决方案,从理论上不能保证满足要求,因为查询输出记录的顺序不一定是记录输入表的顺序。本回答被提问者采纳
参考技术B 你要求的这个查询根本没有严格的顺序问题,所以我觉得只能分步查询:
1.先建一个临时表temp
create table temp
(id identity(1,1),
check_id char(2),
idate datetime
)
go
/*temp表跟你的这个表定义一样*/
2:先查check_id=2 or check_id=4的记录
select *
into temp
from 你的表名
where check_id=2 or check_id=4
group by check_id desc,idate desc
go
3.再查剩下的记录
select *
into temp
from 你的表名
into temp
where check_id!=2 and check_id!=4
group by check_id desc,idate_id desc
go
4.最后查询temp表,即得你要的数据了:
select *
from temp
go

以上是关于sql 分组排序的主要内容,如果未能解决你的问题,请参考以下文章

sql 分组内排序

mySQL分组排序

sql多表分组查询并排序的问题

sql 分组排序

oracle sql分组排序

SQL如何对分组后的结果进行排序并且取前几名