Skip to content
Advertisement

SQL how to fill out first line of group with value and other values to null

Actually i have a select statement which contains a group by

id      id_2  test
90001   7792  abc
90002   7792  abc
90003   7792  abc
94001   7024  efg
94002   7024  efg
94003   7024  efg

I would like this :

id      id_2  test
90001   7792  abc
90002   7792  null
90003   7792  null
94001   7024  efg
94002   7024  null
94003   7024  null

How to do that (test value fill in first row group) with sql (pgsql) ? thanks !

I tried Partition by…

Advertisement

Answer

demo:db<>fiddle

SELECT
    id,
    id_2,
    CASE WHEN row_number = 1 THEN test END as test         -- 2
FROM (
    SELECT
        *,
        row_number() OVER (PARTITION BY id_2 ORDER BY id)  -- 1
    FROM mytable
) s
  1. Enumerate all records of an ordered group to find the first one using the row_number() window function
  2. Keep the value if the row number is 1, NULL else
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement