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

求教高手-根据两列的时间列进行统一[倒序]排序
表中分别有如下所示4个列,其中DialogueTime可能为NULL,ComeTimeC也可能为NULL。但是两列不可能同时为NULL。
要求:DialogueTime若不为NULL,则取DialogueTime进行排序,无视ComeTimeC。
  当DialogueTime为NULL时,则取ComeTimeC排序
HTML code

ID           NAME                   DialogueTime                                ComeTimeC
1            小黑                   2012-02-18 08:33:39                     2012-02-25 23:57:39
2            小红                         NULL                              2015-03-18 08:33:39
3            小白                   2014-03-18 08:33:39                     2010-03-18 08:33:39
4            小青                   2012-03-18 08:33:39                              NULL
5            小紫                         NULL                              2010-03-18 08:33:39



我想要的输出结果为(注:我要的是倒序排列,既日期大的显示在前面)->
HTML code

ID           NAME                     DialogueTime                                ComeTimeC
2            小红                          NULL                             2015-03-18 08:33:39
3            小白                   2014-03-18 08:33:39                     2010-03-18 08:33:39
4            小青                   2012-03-18 08:33:39                              NULL
5            小紫                            NULL                           2010-03-18 08:33:39
1            小黑                   2012-02-18 08:33:39                     2012-02-25 23:57:39




希望高手指点。。。

------解决方案--------------------
要求:DialogueTime若不为NULL,则取DialogueTime进行排序,无视ComeTimeC。
当DialogueTime为NULL时,则取ComeTimeC排序

order by (case when DialogueTime is null then ComeTimeC else DialogueTime end) --desc
------解决方案--------------------
SQL code
use Tempdb
go
--> --> 
 
if not object_id(N'Tempdb..#T') is null
    drop table #T
Go
Create table #T([ID] int,[NAME] nvarchar(2),[DialogueTime] Datetime,[ComeTimeC] Datetime)
Insert #T
select 1,N'小黑','2012-02-18 08:33:39','2012-02-25 23:57:39' union all
select 2,N'小红',null,'2015-03-18 08:33:39' union all
select 3,N'小白','2014-03-18 08:33:39','2010-03-18 08:33:39' union all
select 4,N'小青','2012-03-18 08:33:39',null union all
select 5,N'小紫',null,'2010-03-18 08:33:39'
Go

Select * from #T  order by isnull([DialogueTime],[ComeTimeC]) desc
/*
2    小红    NULL    2015-03-18 08:33:39.000
3    小白    2014-03-18 08:33:39.000    2010-03-18 08:33:39.000
4    小青    2012-03-18 08:33:39.000    NULL
1    小黑    2012-02-18 08:33:39.000    2012-02-25 23:57:39.000
5    小紫    NULL    2010-03-18 08:33:39.000
*/