Home > database >  Apply Same Transformation to Multiple Returned Columns in SQL
Apply Same Transformation to Multiple Returned Columns in SQL

Time:02-10

I am trying to simplify a query that has much duplication and is doing the same operations to multiple returned values. How can I apply the same d * 10000 operation to e, g, i to simplify this query?

select a, b, c, a   b   c as d,
(a   b   c) * 10000 * e as f,
(a   b   c) * 10000 * g as h,
(a   b   c) * 10000 * i as j
from mytable

CodePudding user response:

You can simplify with a lateral join and values, such as

select a, b, c, a   b   c as d,
  v * e as f,
  v * g as h,
  v * i as j
from mytable t,
lateral (values((a   b   c) * 10000))x(v);

Demo Fiddle

  • Related