sql - How to make GROUP BY as a parameter without using CASE WHEN? -
I have the following table with the following tables and values and types.
Create a table example (fname text, lname text, value int); Enter the values in the example ('doe', 'coin', 123), ('bit', 'coin', 434), ('light', 'coin', 565), ('dogs', 'mem' 183), ('bit', 'mem', 453), ('light', 'mem', 433); Create (name text, zodiac int) as a typed result;
I would like to write a function, which is given by a function to the group. This example works:
declare text $$ my_parameter; Result result []; Start my_parameter = 'last'; Result: = array (when my_premator = 'first' then fender occurs when my_parameter = 'last' then lname end, sum (pay)): Example group from example group when my_parameter = 'first' then fname when my_parameter = 'last 'And then' lname 'end); Increase notices '%', results; End; $$ language plpgsql;
I have been told that when a decision is really expensive, a clear solution is to make the selectors twice:
if my_parameter = 'First' then result: = array (selection line (fname, sum (pay)): resulting from example group fname; end if; If my_parameter = 'last' then the result: = array (selection line (lname, sum (salary)): result from example group by lname; if end;
but it does not change the ugly duplicate code
Is there another way to make the group eligible for the parameter?
If you do not want to use the case
, you can use it:
Choose whistle (name, pay) (e.g. , Where my_parameter = 'first' is the choice of a union Do not, where my_parameter = 'last') salary name, / code> But, in fact, it is better to check, I have not heard that the case
is expensive .
If you think that case
is not expensive, then I still suggest subquery or cte to avoid code duplicates, like:
< Pre-> with as the CT (name, pay) name (select my_parameter = 'first' then fname when my_parameter = 'last' then name as name, salary, for example) name not Gm, zodiac sign (salary) from whistle group
Comments
Post a Comment