TSQL如何使用" ALL"?订购参数值

时间:2011-12-01 19:35:52

标签: tsql ssrs-2008 union

我正在开发SSRS 2008报告,并且我试图让我的一个存储过程输出“-All-”与此参数的其他可能值联合,其中“-All-”显示为第一个值。相反,“ - All-”按字母顺序排序,以便首先列出“Adams”。如何让“-All-”成为第一名? (注意,这个参数是一个uniqueidentifier,所以我不能使“-All-”= -1。这是我现在的T-SQL代码:

Select NULL As [client_id], NULL AS [id_no], '-All-' As [full_name], '-All-' As [id_and_name]
UNION ALL
Select Distinct [people_id] AS [client_id], [id_no], [full_name], [full_name] + ' : ' + [id_no] AS [id_and_name]
From [evolv_cs].[dbo].[service_track_current_view] With (NoLock) 
Order By [full_name]

当我尝试这段代码时:

Select NULL As [client_id], NULL AS [id_no], '-All-' As [full_name], '-All-' As [id_and_name]
UNION ALL
Select Distinct [people_id] AS [client_id], [id_no], [full_name], [full_name] + ' : ' + [id_no] AS [id_and_name]
From [evolv_cs].[dbo].[service_track_current_view] With (NoLock) 
Order By 
CASE [full_name] WHEN '-All-' THEN 0 ELSE 1 END,

[FULL_NAME]

我收到了这个错误:

Msg 207, Level 16, State 1, Line 6
Invalid column name 'full_name'.
Msg 104, Level 16, State 1, Line 6
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

2 个答案:

答案 0 :(得分:1)

<强>更新
事实证明,我们不能使用ORDER BY子句中我们在查询中指定的列名。但是,这个更新的代码应该可以使用:

SELECT * FROM (
    Select NULL As [client_id], NULL AS [id_no], '-All-' As [full_name], '-All-' As [id_and_name]
    UNION ALL
    Select Distinct [people_id] AS [client_id], [id_no], [full_name], [full_name] + ' : ' + [id_no] AS [id_and_name]
    From [evolv_cs].[dbo].[service_track_current_view] With (NoLock) 
)tbl
ORDER BY
    CASE [full_name] WHEN '-All-' THEN 0 ELSE 1 END,
    [full_name]

也就是说,您首先根据值是否为-All-进行排序,并且在这两个组中,您按实际值本身排序。

答案 1 :(得分:1)

如果您可以添加列,则可以将0 AS [sort_value]添加到联合的第一部分,将1 AS [sort_value]添加到联合的第二部分。

然后只需Order By [sort_value],[full_name]

相关问题