在Common Table Expression中按问题排序

时间:2012-01-23 09:53:25

标签: sql common-table-expression

我在下面显示的存储过程中使用Common Table Expression我想按升序显示国家/地区名称

1   | India
2   | Bangladesh
3   | Srilanka
4   | Nepal
5   | Japan

表达式如下

WITH CTECountry as
(
SELECT 
   CountryID,
   CountryName 
FROM dbo.Country
ORDER BY CountryName ASC        
)
SELECT 
*
FROM CTECountry 
UNION SELECT '0','--Select--'

5 个答案:

答案 0 :(得分:5)

ORDER BY适用于整个UNION(在这种情况下需要ALL)。

在任何情况下,最外层的ORDER BY子句可以保证对结果进行排序。除某些情况外,内部和中间ORDER BY子句没有任何影响或产生错误。

WITH CTECountry as
(
SELECT 
   CountryID,
   CountryName 
FROM dbo.Country
)  
SELECT 
   CountryID,
   CountryName 
FROM CTECountry 
UNION ALL
SELECT '0','--Select--'
ORDER BY CountryName ASC   -- goes here

编辑,我怀疑你在上面的评论之后想要这个

WITH CTECountry as
(
SELECT 
   CountryID,
   CountryName,
   1 AS SortOrder
FROM dbo.Country
UNION ALL
SELECT '0','--Select--', 2
)  
SELECT 
   CountryID,
   CountryName 
FROM 
   CTECountry
ORDER BY
   SortOrder, CountryName ASC

答案 1 :(得分:1)

类似于GBN的答案,但稍微简单一些:

WITH CTECountry as
(
SELECT 
   CountryID,
   CountryName 
FROM dbo.Country
)
SELECT 
*
FROM CTECountry 
UNION SELECT 0,'--Select--'
ORDER BY sign(CountryID) DESC, CountryName ASC

(假设CountryID实际上是数字,而不是字符串)

答案 2 :(得分:0)

通过将查询修改为

解决了问题
  

WITH CTECountry as   (      选择         ROW_NUMBER()过了         (       按国家名称ASC排序         )作为Rownumber,         CountryID,
        国家或地区名称
     从         dbo.Country      按国家名称排序ASC
  )   SELECT * FROM CTECountry UNION SELECT'0',' - 选择 - '

答案 3 :(得分:0)

在SQL SERVER的情况下,我发现有另一种方法可以做到这一点,尽管它不完美。您将TOP 999999999999添加到CTE:

WITH CTECountry as
(
SELECT TOP 99999999999
   CountryID,
   CountryName 
FROM dbo.Country
ORDER BY CountryName ASC        
)
SELECT 
*
FROM CTECountry 
UNION SELECT '0','--Select--'

这个数字并不重要,但你希望它足够高,以至于你永远不会真实地击中它。它有点hacky但是如果你出于某种原因需要快速解决方法,那么

答案 4 :(得分:0)

添加到@Arch答案,您可以在sql server

中执行以下操作
 WITH CTECountry as
(
SELECT TOP 100 PERCENT
   CountryID,
   CountryName 
FROM dbo.Country
ORDER BY CountryName ASC        
)
SELECT 
*
FROM CTECountry 
UNION SELECT '0','--Select--'

请参阅this question