2

I need to write a function in Postgresql where the function will return a table with three columns. These three columns will be populated from three different queries. I want to know how to club these three queries in a single function.

CREATE OR REPLACE FUNCTION ytd(MMYY character varying, MMYY1 character varying)
  RETURNS TABLE(name character varying, ratio bigint, ratio1 bigint) AS
$BODY$

BEGIN
RETURN query
SELECT col1 as name from t1, 
Select col2 as ratio from t2,
Select col3 as ratio1 from t3


END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;
ALTER FUNCTION ydt2(MMYY character varying, MMYY1 character varying)
  OWNER TO postgres;

Same parameter will be passed in each sql

5
  • 1
    Why don't you use JOIN if you have relation between these tables? Commented Jul 16, 2015 at 13:03
  • Tables are not related. How do I join three queries? Commented Jul 16, 2015 at 13:09
  • Then how could you tell which name goes with which ratio? Commented Jul 16, 2015 at 13:15
  • I want quer1 goes to name and so on...I am new in database..so i want to know is it possible to club multiple queries in single function? Commented Jul 16, 2015 at 13:28
  • Could you provide more information about the three table structures? Put the code in this way you could also susbstitute the FUNCTION with a PROCEDURE and make use of three output parameters. Commented Jul 16, 2015 at 15:11

1 Answer 1

3

If the method of how you JOIN the three data-sets is irrelevant (and as you say they are unrelated), then merging the three data-sets should be quite trivial (See SQL Fiddle).

This SQL (below) should exemplify with an example:

CREATE TABLE a (a1 INTEGER);
CREATE TABLE b (b1 INTEGER);
CREATE TABLE c (c1 INTEGER);

INSERT INTO a VALUES(11), (12);
INSERT INTO b VALUES(21), (22);
INSERT INTO c VALUES(31), (32);

WITH 
  aa AS (SELECT row_number() OVER () AS r, * FROM a),
  bb AS (SELECT row_number() OVER () AS r, * FROM b),
  cc AS (SELECT row_number() OVER () AS r, * FROM c)
SELECT r, a1, b1, c1
FROM aa
  JOIN bb
    USING (r)
  JOIN cc
    USING (r)
Sign up to request clarification or add additional context in comments.

Comments

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.