1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

  2. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

How to distinct column by starting from earliest/latest row with SQL query?

Discussão em 'Outras Linguagens' iniciado por Stack, Abril 13, 2021.

  1. Stack

    Stack Membro Participativo

    how can I distinct the column but the row were removed is from the earliest found/retain the last?

    I have tried some ways, but all of them not worked.
    below is the raw, column that I want to work with

    parent_item_id
    ------------------------------------
    9B3E7A72-D36A-42D3-A04C-186DEC409F93
    942E1854-9EB4-4C19-8A1E-4FCC4953B50C
    E75C7294-F0C4-4C6E-8C12-DF5FBC93FA3B
    942E1854-9EB4-4C19-8A1E-4FCC4953B50C
    942E1854-9EB4-4C19-8A1E-4FCC4953B50C


    below is the ways I tried:

    1. using the default behaviour of distinct like this.
      query:

    WITH tree AS (SELECT distinct(ic.parent_item_id) FROM dbo.item_combination ic, dbo.product p WHERE ic.child_item_id != p.item_id
    UNION ALL
    SELECT ic.parent_item_id FROM tree t, dbo.item_combination ic WHERE t.parent_item_id=ic.child_item_id
    )
    SELECT DISTINCT (parent_item_id) from tree


    result:

    parent_item_id
    --
    9B3E7A72-D36A-42D3-A04C-186DEC409F93
    942E1854-9EB4-4C19-8A1E-4FCC4953B50C
    E75C7294-F0C4-4C6E-8C12-DF5FBC93FA3B

    1. using row_number like this. but based on my logic it should change the order but why the final result is the same as way 1? query:

    WITH tree AS (SELECT distinct(ic.parent_item_id) FROM dbo.item_combination ic, dbo.product p WHERE ic.child_item_id != p.item_id
    UNION ALL
    SELECT ic.parent_item_id FROM tree t, dbo.item_combination ic WHERE t.parent_item_id=ic.child_item_id
    )
    SELECT DISTINCT(parent_item_id) FROM
    (
    SELECT t.parent_item_id, [row_number]=ROW_NUMBER() OVER(ORDER BY (SELECT 1)) FROM tree t ORDER BY [row_number] DESC OFFSET 0 ROWS
    ) r
    group by r.parent_item_id, r.[row_number]


    result:

    parent_item_id
    --
    9B3E7A72-D36A-42D3-A04C-186DEC409F93
    942E1854-9EB4-4C19-8A1E-4FCC4953B50C
    E75C7294-F0C4-4C6E-8C12-DF5FBC93FA3B


    the result I want/expected is like this.

    parent_item_id
    --
    9B3E7A72-D36A-42D3-A04C-186DEC409F93
    E75C7294-F0C4-4C6E-8C12-DF5FBC93FA3B
    942E1854-9EB4-4C19-8A1E-4FCC4953B50C

    Continue reading...

Compartilhe esta Página