prasingh
prasingh

Reputation: 472

Fetch records based on two column. One record if both column have same value else 2 records

I have use-case wherein, we have a table lets say table_a

table_a have multiple columns, Lets consider 3 a, b & c.

table_a

|a|b|c|
|1|1|x|
|2|3|y|

Output required

  1. If a and b have same value then required one records.
  2. If a and b have different value then required two records.

Expected output:

|a|b|c|
|1|1|x|
|2|3|y|
|2|3|y|

Upvotes: 1

Views: 134

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270633

You can do this without arrays using a lateral join:

select t.a, t.b, t.c
from t cross join lateral
     (values (1), (2)) n(n)
where n.n = 1 or t.a <> t.b;

Upvotes: 0

S-Man
S-Man

Reputation: 23746

demo:db<>fiddle

SELECT
    t.*
FROM
    table_a t,
    unnest(CASE WHEN a = b THEN ARRAY[1] ELSE ARRAY[1,1] END)

A set-returning function may duplicate the records. In this case the unnest() function expands the array which is created as parameter. If a equals b then an array is created with only one element. In this case the unnest() function expands only one record. Otherwise a two-element-array is created which results in an expansion with two records.

Upvotes: 2

Related Questions