0

I want to "dynamically" create the result columns in a PostgreSQL query. I have these tables:

CREATE SEQUENCE users_id;
CREATE TABLE users (
  id INT PRIMARY KEY NOT NULL DEFAULT NEXTVAL('users_id'),
  name VARCHAR(128) NOT NULL
);

CREATE SEQUENCE quota_rules_id;
CREATE TABLE quota_rules (
  id INT PRIMARY KEY NOT NULL DEFAULT NEXTVAL('quota_rules_id'),
  user_id INT REFERENCES users(id),
  rule VARCHAR(255) NOT NULL
);
CREATE INDEX user_id_index ON quota_rules(user_id);

INSERT INTO users (name) VALUES ('myname'); -- id=1
INSERT INTO quota_rules (user_id, rule) VALUES (1, 'a');
INSERT INTO quota_rules (user_id, rule) VALUES (1, 'b');
INSERT INTO quota_rules (user_id, rule) VALUES (1, 'c');

And want a query that returns this (1 row):

SELECT ............ user_id = 1;
name   | quota_rule | quota_rule2 | quota_rule3
myname | a          | b           | c

1 Answer 1

1

Check out the crosstab function of the tablefunc module

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! All the examples I've seen goes something like: SELECT * FROM crosstab('..') AS (field1, field2, field3); Is it possible to dynamically make the right side? Ex: If there were five rows in quota_rules, I'd end up with (name,quota_rule,quota_rule2,quota_rule3,quota_rule4,quota_rule5)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.