3

My query is

SELECT 
    (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) AS earnings 
    ,(`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`) AS deductions 
   ,(earnings - deductions) AS net_salary 
FROM 
    salary

and im getting an error that unknown column earnings and deductions because these are column alias not column name .. Any solution? Thanks in advance

McNets
  • 23,979
  • 11
  • 51
  • 89
Tanveer Jafri
  • 35
  • 1
  • 1
  • 4

3 Answers3

3

Additionally to previous answers.

1) You can try to use user-defined variables:

SELECT 
    @earnings := (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) AS earnings ,
    @deductions := (`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`) AS deductions,
    @earnings - @deductions AS net_salary 
FROM 
    salary
    -- , (SELECT @earnings:=0, @deductions:=0) vars

Documentation do not guarantee the calculations order, but in practice all calculations are performed from left to right.

2) If your MySQL version is 8+, you can use CTE:

WITH cte AS (
SELECT 
    (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) AS earnings, 
    (`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`) AS deductions 
FROM 
    salary
)
SELECT earnings, deductions, (earnings - deductions) AS net_salary
FROM cte;
Akina
  • 20,750
  • 2
  • 20
  • 22
2

You cannot use an alias in the same SELECT list.

You can either repeat the expressions:

SELECT 
    (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) 
        AS earnings , 
    (`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`)
        AS deductions ,
    (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) 
    -
    (`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`)
        AS net_salary
FROM salary ;

or use a derived table:

SELECT 
    earnings , 
    deductions ,
    earnings - deductions AS net_salary
FROM 
  (
    SELECT 
        (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) 
            AS earnings , 
        (`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`)
            AS deductions
    FROM salary 
  ) AS dt ;
ypercubeᵀᴹ
  • 99,450
  • 13
  • 217
  • 306
1

Replace alias with the computed columns.

SELECT 
    (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) AS earnings 
    ,(`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`) AS deductions 
    ,(`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) - (`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`)  AS net_salary 
FROM 
    salary;
McNets
  • 23,979
  • 11
  • 51
  • 89