Duplicate Select Postgresql output

Asked

Viewed 467 times

2

I have a record that is a receipt, and in select, I want the line to come duplicated. Ex:

Select * from recibos where codigo =1;

Upshot:

codigo|cliente|valor|emitente|data
  1    Fulano   10    Ciclano  19/10/2017

Result I need:

codigo|cliente|valor|emitente | data       |  via
  1    Fulano   10    Ciclano   19/10/2017     1
  1    Fulano   10    Ciclano   19/10/2017     2

2 answers

1


Assuming:

CREATE TABLE tb_recibos (
    codigo integer,
    cliente text,
    valor integer,
    emitente text,
    data date
);

INSERT INTO tb_recibos ( codigo, cliente, valor, emitente, data )
VALUES ( 1, 'Fulano', 10, 'Ciclano', '2017.10.19' );

Solution #1 (Less compact, complex plane ):

SELECT
    r.codigo,
    r.cliente,
    r.valor,
    r.emitente,
    r.data,
    s AS via
FROM
    tb_recibos AS r 
CROSS JOIN
    generate_series( 1, 2 ) AS s
WHERE
    codigo = 1;

Solution #2 (More compact, simple flat):

SELECT
    r.codigo,
    r.cliente,
    r.valor,
    r.emitente,
    r.data,
    generate_series( 1, 2 ) as via
FROM
    tb_recibos AS r 
WHERE
    codigo = 1;

See working on Sqlfiddle

  • Thank you Lacobus, funny that in fiddle, the #2 solution has the shortest running time

1

I got the result waiting using the following syntax:

 Select 
     r.*,
     s.via 
 from recibos r 
 inner join generate_series(1,2) s(via) on 1=1
 where codigo = 1;

If anyone has another suggestion on how to get the same result, thank you.

  • 1

    The use of a CROSS JOIN dispenses with the use of ON.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.