+ -
当前位置:首页 → 问答吧 → 求教SQL语句的排序,不够分,请版主大人转移

求教SQL语句的排序,不够分,请版主大人转移

时间:2011-12-28

来源:互联网

select a,b from c order by b desc, a desc

表记录类似:
id a b
1 1 2009
2 1 2008
3 2 2011
4 3 2011
5 5 2012
6 6 2013


主要按b列排序,但是a 列为 5的时候要放最后,如果不用 UNION、联合查询 要怎么写order 后面的? 这个是要分页的!

作者: ieeeei   发布时间: 2011-12-28

SQL code
select a,b from c order by (case when a=5 then 1800 else b end) desc,a desc

作者: qianjin036a   发布时间: 2011-12-28

SQL code
create table c(id int,a int,b int)
insert into c select 1,1,2009
insert into c select 2,1,2008
insert into c select 3,2,2011
insert into c select 4,3,2011
insert into c select 5,5,2012
insert into c select 6,6,2013
go
select a,b from c order by (case when a=5 then 1800 else b end) desc,a desc
/*
a           b
----------- -----------
6           2013
3           2011
2           2011
1           2009
1           2008
5           2012

(6 行受影响)
*/
go
drop table c

作者: qianjin036a   发布时间: 2011-12-28

原来case when也可以用在 order 里,谢谢大神!

作者: ieeeei   发布时间: 2011-12-28

问题已经解决了!谢谢啊!

作者: ieeeei   发布时间: 2011-12-28

多条件排序,我是跟晴天大大学的..
SQL code
use test
go
if object_id('t1') is not null
drop table t1
go
create table t1(id int,a int,b int)
insert t1
select 1, 1, 2009 union all
select 2, 1, 2008 union all
select 3, 2, 2011 union all
select 4, 3, 2011 union all
select 5, 5, 2012 union all
select 6, 6, 2013
go
select * from t1 order by case  when a=5 then 1 else 0 end ,b
/*
id      a        b
---     --      ----
2    1    2008
1    1    2009
3    2    2011
4    3    2011
6    6    2013
5    5    2012
*/
go
drop table t1

作者: xiaolinyouni   发布时间: 2011-12-28

引用 1 楼 qianjin036a 的回复:

SQL code
select a,b from c order by (case when a=5 then 1800 else b end) desc,a desc



晴天,虽然上个月跟你学了多条件排序,但是真心不透彻,求解释这句.

作者: xiaolinyouni   发布时间: 2011-12-28

因为这个需求是要以年份排序,但a=5的,不管年份都要排在后面,另外由于是降序排列,因此,当a=5的时候,把年份改成一个不可能再小的年份 1800,这样它就排到最后去了,其他的,按原年份排.还可以写成:
select a,b from c order by (case when a=5 then b-1000 else b end) desc,a desc

作者: qianjin036a   发布时间: 2011-12-28

引用 7 楼 qianjin036a 的回复:

因为这个需求是要以年份排序,但a=5的,不管年份都要排在后面,另外由于是降序排列,因此,当a=5的时候,把年份改成一个不可能再小的年份 1800,这样它就排到最后去了,其他的,按原年份排.还可以写成:
select a,b from c order by (case when a=5 then b-1000 else b end) desc,a desc


so dai si nai!

多谢晴天了.

作者: xiaolinyouni   发布时间: 2011-12-28

給你轉到技術區

作者: roy_88   发布时间: 2011-12-28