Skip to content
Advertisement

Alias for a mysql case statement

I would like to set an alias for the case statement in the following query. The query works fine but the last column header shows as the case statement in full. You can have a look at what I mean at dbfiddle. I am trying to get the difference between the current salary at a row and the next salary found for that employee in a list of employees.

select r.totalSalary, r.nextTotalSalary , 
 (case when isnull(r.nextTotalSalary)= 1 then r.totalSalary
    else nextTotalSalary
    end ) - r.totalSalary 
 from (
    SELECT 
        pi.empid,
        pi.totalSalary,
        LEAD(pi.totalSalary,1) OVER (
            PARTITION BY pi.empid
            ORDER BY pi.effectivefrom ) nextTotalSalary
    FROM 
     Report pi where pi.empid = 200 ) r ;

When i try to place an alias as end as nextTotalSalary the query won’t execute. Error is “Select is not valid at this position for this server version ..”

How can i set an alias for the third column?

Advertisement

Answer

You can use AS. For example:

select r.totalSalary,  r.nextTotalSalary ,  ( case  when isnull(r.nextTotalSalary)= 1 then r.totalSalary
else nextTotalSalary
end  ) - r.totalSalary as nextTotalSalary
from (
SELECT 
    pi.empid,
    pi.totalSalary,
    LEAD(pi.totalSalary,1) OVER (
        PARTITION BY pi.empid
        ORDER BY pi.effectivefrom ) nextTotalSalary
FROM 
 Report pi where pi.empid = 200 ) r ;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement