12
Practice+
1. Energy expenses must be distributed between different
departments in proportion to their headcount (the list of
departments is stored in a table).
Create a function that takes the total energy cost as an argument
and saves the distributed expenses in different table rows.
The values are rounded to cents; the sum of expenses of all
departments must exactly match the total cost.
2. Create a set returning function that simulates merge sort. The
function should take two cursor variables; both cursors are
already open and return sorted integers in non-decreasing order.
It must return a single sorted sequence of integers from both
sources.
1. We can use the following table:
CREATE TABLE depts(
id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
employees integer,
expenses numeric(10,2)
);
INSERT INTO depts(employees) VALUES (10),(10),(10);
A possible implementation:
FUNCTION distribute_expenses(amount numeric) RETURNS void;
If 100.00 is taken as an argument, the expected result is:
expenses
----------
33.33
33.34
33.33
2. A possible implementation:
FUNCTION merge(c1 refcursor, c2 refcursor) RETURNS SETOF integer;
For example, if the first cursor returns the sequence 1, 3, 5, and the second
cursor returns the sequence 2, 3, 4, the expected result is as follows:
merge
-------
1
2
3
3
4
5