使用Case语句作为别名

时间:2018-05-29 19:44:55

标签: sql sql-server sql-server-2017

我正在尝试根据变量

更改列的标题

目前我有

SELECT
    (CASE 
        WHEN GROUPING(CASE @@Role 
                         WHEN 2 THEN Processor 
                         WHEN 3 THEN Reviewer 
                      END) = 1 
           THEN 'Total' 
           ELSE (CASE @@Role 
                    WHEN 2 THEN Processor 
                    WHEN 3 THEN Reviewer 
                 END) 
     END) AS 'User',
    COUNT(EntityId) AS 'Tickets Processed'
FROM
    table
WHERE
    conditions
GROUP BY
    CASE @@Role 
       WHEN 2 THEN Processor 
       WHEN 3 THEN Reviewer 
    END WITH ROLLUP

现在这会返回正确角色所需的数据,但有没有办法根据变量将第二列的标题更改为

COUNT(EntityId) AS CASE @@Role 
                      WHEN 2 THEN 'Tickets Processed' 
                      WHEN 3 THEN 'Tickets Reviewed'  
                   END

编辑:

当前结果的样本:

@@Role = 2 or @@Role = 3

两者都返回:

User        Tickets Processed
-----------------------------
Steve       1
Gerald      3
John        1
Paul        2
Peter       5
Total       12

期望的结果:

@@Role = 2 

User        Tickets Processed
-----------------------------
Steve       1
Gerald      3
John        1
Paul        2
Peter       5
Total       12

@@Role = 3

User        Tickets Reviewed
-----------------------------
Steve       1
Gerald      3
John        1
Paul        2
Peter       5
Total       12

示例数据

EntityID    Processor   Reviewer
----------------------------------
1           Peter       Bob
2           Peter       Paul
3           Peter       Bob
4           John        Paul
5           Peter       Bob
6           Peter       Bob
...

1 个答案:

答案 0 :(得分:0)

您可以使用动态sql,也可以根据@@role变量拆分逻辑:

IF @@Role = 2 THEN {do Query A}
ELSE {do Query B}

但是你绝对不能在非动态查询的上下文中将列别名作为变量值的基础。