简体   繁体   中英

Reuse variables in sql query

I want to know is there a way to reuse variables defined as AS and not to rewrite our code every time or not?

Example

I have such line:

IFNULL((CASE WHEN (((c.gaji_pokok+c.tunjangan+q.jkk+q.jkm)*12)+('c.komisi' * 'c.thr') >= 6000000) then ((c.gaji_pokok+c.tunjangan+q.jkk+q.jkm)*12)+('c.komisi' * 'c.thr')*0.05 ELSE 6000000 end),0) as b_jabatan,

and the next time I need such command I just want to use b_jabatan instead of writing whole line

example

IFNULL((b_jabatan,0) as brutto_tahun,

is that possible?

Use the least() function:

coalesce(least( ((c.gaji_pokok+c.tunjangan+q.jkk+q.jkm)*12)+(c.komisi * c.thr)*0.05, 6000000
              ), 0
        ) as b_jabatan,

You can't reuse an alias in the same scope - left apart the order by clause (and, in MySQL, the group by and having clauses).

You either need to repeat the expression, or use a subquery or CTE (which creates a new scode). So:

select t.*, coalesce(b_jabatan,0) as brutto_tahun, ...
from (
     select
          < your super long expression > as b_jabatan,
          ...
     from ...
) t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM