求sql 语句 order by 两个字段都是 datetime 的有关问题
求sql 语句 order by 两个字段都是 datetime 的问题
请教一个sql语句
a 表中有两个字段 start_time, close_time 都是日期型 ,close_time里面有空值,start_time没有空值,
求一个查询语句,start_time 最新的数据排在最前面同时close_time 为空的排在最前面, close_time不为空的最新的排在前面。
形成这样的格式 ,谢谢
2012-3-18 空
2012-3-2 空
2012-3-15 2012-3-4
2012-3-4 2012-3-3
------解决方案--------------------
------解决方案--------------------
另外,按照你上面的2个,下面的代码,应该就是你想要的:
请教一个sql语句
a 表中有两个字段 start_time, close_time 都是日期型 ,close_time里面有空值,start_time没有空值,
求一个查询语句,start_time 最新的数据排在最前面同时close_time 为空的排在最前面, close_time不为空的最新的排在前面。
形成这样的格式 ,谢谢
2012-3-18 空
2012-3-2 空
2012-3-15 2012-3-4
2012-3-4 2012-3-3
------解决方案--------------------
select * from [Table]
order by case when close_time is null then 0 else 1 end,,close_time desc,start_time desc
------解决方案--------------------
另外,按照你上面的2个,下面的代码,应该就是你想要的:
declare @table table(start_time datetime,close_time datetime)
insert into @table(start_time,close_time)
values ('2012-3-2' ,null),
('2012-3-15' ,'2012-3-4'),
('2012-3-4' ,'2012-3-3'),
('2012-3-18' ,null)
select *
from @table
order by case when close_time IS null
then 1
else 0
end desc ,
case when close_time IS null
then start_time
else close_time
end desc
/*
start_time close_time
2012-03-18 00:00:00.000 NULL
2012-03-02 00:00:00.000 NULL
2012-03-15 00:00:00.000 2012-03-04 00:00:00.000
2012-03-04 00:00:00.000 2012-03-03 00:00:00.000
*/