日期:2014-05-18  浏览次数:20511 次

双字段排序
我有一个表,记录是这样的 
id 开始时间 过期时间 
1 2008-11-05 2008-12-05 
2 2008-11-09 2009-10-17 
3 2008-11-12 2008-12-18 
4 2008-11-18 2009-06-08 

我想得到以下结果: 
id 开始时间 过期时间 
4 2008-11-18 2009-06-08 
2 2008-11-09 2009-10-17 
3 2008-11-12 2008-12-18 
1 2008-11-05 2008-12-05 

我是代码是这样写的:where jytype='优惠券' and Commend_Info=0 Order by 开始时间 desc,过期时间 desc 
但是无效,请高手帮忙

------解决方案--------------------
楼主你的结果不对,应该是这个。
SQL code
4    2008-11-18          2009-06-08 
3    2008-11-12          2008-12-18 
2    2008-11-09          2009-10-17 
1    2008-11-05          2008-12-05

------解决方案--------------------
还是没猜出来,看看是不是这个:

SQL code
if object_id('tb') is not null drop table tb 
 go 
create table tb([id] int,[开始时间] datetime,[过期时间] datetime)
insert tb select 1,'2008-11-05','2008-12-05'
union all select 2,'2008-11-09','2009-10-17'
union all select 3,'2008-11-12','2008-12-18'
union all select 4,'2008-11-18','2009-06-08'
go
select * from tb order by datediff(dd,开始时间,过期时间)  desc
/*
id          开始时间                    过期时间
----------- ----------------------- -----------------------
2           2008-11-09 00:00:00.000 2009-10-17 00:00:00.000
4           2008-11-18 00:00:00.000 2009-06-08 00:00:00.000
3           2008-11-12 00:00:00.000 2008-12-18 00:00:00.000
1           2008-11-05 00:00:00.000 2008-12-05 00:00:00.000

(4 行受影响)
*/

------解决方案--------------------
id 开始时间 过期时间 
4 2008-11-18 2009-06-08 
2 2008-11-09 2009-10-17 
3 2008-11-12 2008-12-18 
1 2008-11-05 2008-12-05 

是不是ID先偶后奇,开始时间DESC,国旗时间DESC??
------解决方案--------------------
SQL code

--是不是先过期的后未过期的,然后按天数
if object_id('tb') is not null drop table tb 
 go 
create table tb([id] int,[开始时间] datetime,[过期时间] datetime)
insert tb select 1,'2008-11-05','2008-12-05'
union all select 2,'2008-11-09','2009-10-17'
union all select 3,'2008-11-12','2008-12-18'
union all select 4,'2008-11-18','2009-06-08'
go

SELECT * FROM tb ORDER BY CASE WHEN DATEDIFF(DD,[过期时间],GETDATE()) < 0 THEN 0 ELSE 1 END,
ABS(DATEDIFF(DD,[过期时间],GETDATE()))


4    2008-11-18 00:00:00.000    2009-06-08 00:00:00.000
2    2008-11-09 00:00:00.000    2009-10-17 00:00:00.000
3    2008-11-12 00:00:00.000    2008-12-18 00:00:00.000
1    2008-11-05 00:00:00.000    2008-12-05 00:00:00.000