2013-03-03 146 views
2

我想排序日期,並使用此代碼:升序排序日期

SELECT  TID, TName, TOrder 
FROM   tblOrder 
ORDER BY TOrder 

結果:

1 maikel空

5埃米爾空

4 kabol 1

3 samin 2

2 mihad 3

但我想這樣的結果:

4 kabol 1

3 samin 2

2 mihad 3

1 maikel空

5 emil null

請幫我升序排序。

+0

的數據庫是你的工作? – 2013-03-03 07:51:08

回答

5
SELECT TID, TName, TOrder 
FROM tblOrder 
ORDER BY CASE WHEN TORDER IS NULL THEN 1 ELSE 0 END, 
      TOrder 

的Linq:

var x = from a in tblOrder 
     orderby (a.TORDER == null ? 1 : 0), a.TORDER 
     select a 
+0

woooooooow :-)其正確:-)請將此代碼轉換爲LINQ.thx – 2013-03-03 07:44:10

+0

@BakakSaeedi查看我的更新。 – 2013-03-03 07:50:45

0

您可以使用COALESCE

SELECT  TID, TName, TOrder 
FROM   tblOrder 
ORDER BY COALESCE(TOrder,'9999-12-31 23:59:59.997') 
0

這是SQL Server的最簡單的方法:

SELECT TID, TName, TOrder 
FROM tblOrder 
ORDER BY isnumeric(TOrder) DESC, TOrder 

對於其他數據庫如MySQL和PostgreSQL,有簡單的解決方案:

SELECT TID, TName, TOrder 
FROM tblOrder 
ORDER BY TOrder IS NULL, TOrder 

對於Oracle和PostgreSQL,該工程,並利用可能的索引對TOrder:

SELECT TID, TName, TOrder 
FROM tblOrder 
ORDER BY TOrder ASC NULLS LAST 
0

看一看這個查詢和Fiddle

SELECT TID, TName, TOrder INTO #TempTab 
FROM   tblOrder 
WHERE TOrder IS NOT NULL 
ORDER BY TOrder 
SELECT * FROM #TempTab 
UNION ALL 
SELECT  TID, TName, TOrder 
FROM   tblOrder 
WHERE TOrder IS NULL;