如果所有空值按ID排序,则MSSQL将空连接顺序保留为空

时间:2013-01-14 07:36:16

标签: sql sql-server sql-order-by

我有这个mssql查询

SELECT TOP 50 [id], [title], [url], [icon], linkstats.visits 
FROM [websites] LEFT OUTER JOIN [linkstats] ON websites.id=linkstats.lid AND linkstats.code=@country 
WHERE (([country] = @country OR [country]= 'all') AND 
      ([hot] = @hot)) 
ORDER BY linkstats.visits DESC

我想通过空值排序到最后,如果所有都是空的,那么按ID排序 怎么做?!

1 个答案:

答案 0 :(得分:0)

使用CASE

SELECT TOP 50 [id], [title], [url], [icon], linkstats.visits 
FROM [websites] LEFT OUTER JOIN [linkstats] ON websites.id=linkstats.lid AND linkstats.code=@country 
WHERE (([country] = @country OR [country]= 'all') AND 
      ([hot] = @hot)) 
ORDER BY CASE WHEN linkstats.lid IS NULL THEN 1 ELSE 0 END,
         linkstats.visits DESC