将行强制到使用别名的查询结果的顶部

时间:2014-09-30 20:17:38

标签: sql sql-server

我有一个ListBox,它使用以下语句填充SQL查询:

SELECT '-1' as [Value], 'All' as [Text] 
UNION ALL 
SELECT DISTINCT user_id AS [Value], user_L_name AS [Text] 
FROM [issue]
Order by [Text]

我试图在“全部”之后按字母顺序排列所有记录,同时保持“全部”位于顶部。

如果我有这样的ORDER BY子句:

ORDER BY CASE WHEN [Text] = '-1' THEN 0 ELSE 1 END

我收到此错误:

Invalid column name 'Text'.

非常感谢任何帮助。感谢

1 个答案:

答案 0 :(得分:0)

您可以在子查询中执行此操作。我还假设您要检查[文字]是否是"所有"而不是" -1"

SELECT  [Value], [Text]
FROM
(
    SELECT '-1' as [Value], 'All' as [Text] 
    UNION ALL 
    SELECT DISTINCT user_id AS [Value], user_L_name AS [Text] 
    FROM [issue]
) A
Order by Case When [Text] = 'All' Then 0 Else 1 End, [Text]

或者,您可以Order By [值]:

Order by Case When [Value] = '-1' Then 0 Else 1 End, [Text]