Home > Enterprise >  Can you use END AS result in a case statement for more data?
Can you use END AS result in a case statement for more data?

Time:09-28

So I am trying to use the result from the end as on this query, to then make a new column. I need to compare PerformanceTotal with the Total, specifically something simple like PerformanceTotal - total = AmountDifference, and I'm not sure how to do this, I have the SQL query here:

select
    EmployeeNumber,
    Approvals as TotalApprovals,
    base,
    bonus,
    base   bonus as total,
    case
    when Approvals <= 19 then approvals * 50   0
    when approvals > 19 and approvals <= 39 then ((approvals - 19) * 70)   (50*19)
    when approvals > 39 and approvals <= 59 then ((approvals - 39) * 80)   (50*19)   (70*20)
    when approvals > 59 and approvals <= 99 then ((approvals - 59) * 90)   (50*19)   (70*20)   (80*20)
    when approvals > 99 then ((approvals - 99) * 100)                      (50*19)   (70*20)   (80*20)   (90*40)
    end as PerformanceTotal
from
(select
EmployeeNumber,
sum(applicationsapproved) as Approvals,
sum(BaseCalculation) as Base,
sum(BonusCalcuation) as Bonus
from compensation
where EmployeeNumber = '100032' and ActivityYear='2019'
and ApplicationsApproved > 0
group by EmployeeNumber
) as aa

so yeah, basically I want to use the "PerformanceTotal" result data, and I'm not sure how or if it's even possible.

Thank you!

CodePudding user response:

You could place an outer query around what you have already and do your math in the upper query setting an alias for that structure at the bottom. Some DBMS like Teradata allow in-line use of these columns but not SSMS as far as I am aware.

select
aaa.PerformanceTotal
, aaa.total
, aaa.PerformanceTotal - aaa.total AS AmountDifference
FROM
(
select
    EmployeeNumber,
    Approvals as TotalApprovals,
    base,
    bonus,
    base   bonus as total,
    case
    when Approvals <= 19 then approvals * 50   0
    when approvals > 19 and approvals <= 39 then ((approvals - 19) * 70)   (50*19)
    when approvals > 39 and approvals <= 59 then ((approvals - 39) * 80)   (50*19)   (70*20)
    when approvals > 59 and approvals <= 99 then ((approvals - 59) * 90)   (50*19)   (70*20)   (80*20)
    when approvals > 99 then ((approvals - 99) * 100)                      (50*19)   (70*20)   (80*20)   (90*40)
    end as PerformanceTotal
from
(select
EmployeeNumber,
sum(applicationsapproved) as Approvals,
sum(BaseCalculation) as Base,
sum(BonusCalcuation) as Bonus
from compensation
where EmployeeNumber = '100032' and ActivityYear='2019'
and ApplicationsApproved > 0
group by EmployeeNumber
) as aa
) as aaa
  • Related