Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7081063
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T06:52:25+00:00 2026-05-28T06:52:25+00:00

I’m not good at postgres functions. Could you help me out? Say, I have

  • 0

I’m not good at postgres functions. Could you help me out?
Say, I have this db:

name    | round   |position | val
-----------------------------------
A       | 1       | 1       | 0.5
A       | 1       | 2       | 3.4
A       | 1       | 3       | 2.2
A       | 1       | 4       | 3.8
A       | 2       | 1       | 0.5
A       | 2       | 2       | 32.3
A       | 2       | 3       | 2.21
A       | 2       | 4       | 0.8

I want to write a Postgres function that can loop from position=1 to position=4 and calculate the corresponding value. I could do this in python with psycopg2:

import psycopg2
import psycopg2.extras

conn = psycopg2.connect("host='localhost' dbname='mydb' user='user' password='pass'")
CURSOR = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cmd = """SELECT name, round, position, val from mytable"""
CURSOR.execute(cmd)
rows = CURSOR.fetchall()

dict = {}
for row in rows:
    indx = row['round']
    try:
        dict[indx] *= (1-row['val']/100)
    except:
        dict[indx] = (1-row['val']/100)
    if row['position'] == 4:
        if indx == 1:
            result1 = dict[indx]
        elif indx == 2:
            result2 = dict[indx]
print result1, result2

How can I do the same thing directly in Postgres so that it returns a table of (name, result1, result2)

UPDATE:
@a_horse_with_no_name, the expected value would be:

result1 = (1 - 0.5/100) * (1 - 3.4/100) * (1 - 2.2/100) * (1 - 3.8/100) = 0.9043
result2 = (1 - 0.5/100) * (1 - 32.3/100) * (1 - 2.21/100) * (1 - 0.8/100) = 0.6535
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T06:52:25+00:00Added an answer on May 28, 2026 at 6:52 am

    @Glenn gave you a very elegant solution with an aggregate function. But to answer your question, a plpgsql function could look like this:

    Test setup:

    CREATE TEMP TABLE mytable (
      name  text
    , round int
    , position int
    , val double precision
    );
    
    INSERT INTO mytable VALUES
      ('A', 1, 1, 0.5)
    , ('A', 1, 2, 3.4)
    , ('A', 1, 3, 2.2)
    , ('A', 1, 4, 3.8)
    , ('A', 2, 1, 0.5)
    , ('A', 2, 2, 32.3)
    , ('A', 2, 3, 2.21)
    , ('A', 2, 4, 0.8)
    ;
    

    Generic function

    CREATE OR REPLACE FUNCTION f_grp_prod()
      RETURNS TABLE (name text
                   , round int
                   , result double precision)
      LANGUAGE plpgsql STABLE AS
    $func$
    DECLARE
       r mytable%ROWTYPE;
    BEGIN
       -- init vars
       name   := 'A';  -- we happen to know initial value
       round  := 1;    -- we happen to know initial value
       result := 1;
    
       FOR r IN
          SELECT *
          FROM   mytable m
          ORDER  BY m.name, m.round
       LOOP
          IF (r.name, r.round) <> (name, round) THEN   -- return result before round
             RETURN NEXT;
             name   := r.name;
             round  := r.round;
             result := 1;
          END IF;
    
          result := result * (1 - r.val/100);
       END LOOP;
    
       RETURN NEXT;   -- return final result
    END
    $func$;
    

    Call:

    SELECT * FROM f_grp_prod();
    

    Result:

    name | round |  result
    -----+-------+---------------
    A    | 1     | 0.90430333812
    A    | 2     | 0.653458283632
    

    Specific function as per question

    CREATE OR REPLACE FUNCTION f_grp_prod(text)
      RETURNS TABLE (name text
                   , result1 double precision
                   , result2 double precision)
      LANGUAGE plpgsql STABLE AS
    $func$
    DECLARE
       r      mytable%ROWTYPE;
       _round integer;
    BEGIN
       -- init vars
       name    := $1;
       result2 := 1;      -- abuse result2 as temp var for convenience
    
       FOR r IN
          SELECT *
          FROM   mytable m
          WHERE  m.name = name
          ORDER  BY m.round
       LOOP
          IF r.round <> _round THEN   -- save result1 before 2nd round
             result1 := result2;
             result2 := 1;
          END IF;
    
          result2 := result2 * (1 - r.val/100);
          _round  := r.round;
       END LOOP;
    
       RETURN NEXT;
    END
    $func$;
    

    Call:

    SELECT * FROM f_grp_prod('A');
    

    Result:

    name | result1       |  result2
    -----+---------------+---------------
    A    | 0.90430333812 | 0.653458283632
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have some data like this: 1 2 3 4 5 9 2 6
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a jquery bug and I've been looking for hours now, I can't

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.