skip to Main Content

I have something like that, i need to get "triangular" number – created by summing all natural ones from 0 to n.
I have such code, what should i write so i could
SUM name_of_column FROM generate_series?

SELECT n,
    CASE 
      WHEN n > 0 THEN
        SUM value FROM generate_series(1,n)
      ELSE 0
    END
  AS res
FROM triangular

I tried to find "adecvate" PostgreSQL documentation wikilike to see returning table "attributes" of generate_sequence "class"

2

Answers


  1. Are you searching for the cumulative SUM() window function?

    demo:db<>fiddle

    SELECT
        x,
        SUM(x) OVER (ORDER BY x) 
    FROM generate_series(1, 10) AS x  -- second parameter is n
    

    or a simple aggregation?

    demo:db<>fiddle

    SELECT
        SUM(x)
    FROM generate_series(1, 10) AS x  -- second parameter is n
    
    Login or Signup to reply.
  2. If you don’t supply an alias, the name is just "generate_series". I don’t know where this is documented, but it is discoverable by using * and looking at the header:

    select * from generate_series(1,1);
     generate_series
    -----------------
                   1
    

    Or if you assign a column alias, then that is the name:

    select * from generate_series(1,1) as foo(bar);
     bar
    -----
       1
    

    If you supply a table alias but not a column alias, then the column name is a copy of the table name.

    select * from generate_series(1,1) as foo;
     foo
    -----
       1
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search