订购依据请选择作为首选

时间:2017-08-29 10:23:51

标签: sql tsql sql-order-by

我想按升序排序按名称排序 - 请选择 - 作为首选。 有没有办法可以更改我的代码以允许这个? 按ID排序 - 请选择 - 顶部

SELECT DISTINCT 
    firmNetworkID,
    name
FROM dbo.tbl_firmNetwork
UNION
  SELECT '0', '--Please Select--'
ORDER BY firmNetworkID 

按名称排序

    SELECT DISTINCT 
    firmNetworkID,
    name
FROM dbo.tbl_firmNetwork
UNION
  SELECT '0', '--Please Select--'
ORDER BY [name] ASC 

由于

3 个答案:

答案 0 :(得分:3)

SELECT DISTINCT 
    firmNetworkID,
    name,
    1 P
FROM dbo.tbl_firmNetwork
UNION
    SELECT '0', '--Please Select--', 0 
ORDER BY P, [name] ASC

答案 1 :(得分:0)

您可以添加额外的列以进行排序。在联盟之后的选择中你可以放置一些总是先到的东西

SELECT DISTINCT 
firmNetworkID,
name as SortOrder,
name
FROM dbo.tbl_firmNetwork

UNION

SELECT '0','___', '--Please Select--'
ORDER BY SortOrder ASC 

答案 2 :(得分:0)

实际上,不需要额外的列。只需在ORDER BY中使用CASE:

 SELECT firmNetworkID,
     name
 FROM
 (
    SELECT DISTINCT 
        firmNetworkID,
        name
    FROM dbo.tbl_firmNetwork
    UNION ALL
      SELECT '0', '--Please Select--'
    ORDER BY [name] ASC 
 ) AS i
 ORDER BY CASE WHEN i.name='--Please Select--' THEN 1 ELSE 2 END, i.name