0

I have the following data structure

ID  | REFID | NAME
1   | 100   | A
2   | 101   | B
3   | 101   | C

With

SELECT DISTINCT REFID, ID, NAME
FROM my_table
ORDER BY ID

I would like to have the following result:

1   | 100   | A
2   | 101   | B

Colum NAME and ID should contain the MIN or FIRST value.

But actually I get stuck at using MIN/FIRST here.

I welcome every tipps :-)

2
  • Look into ROW_NUMBER, it will do what you need. Commented Aug 11, 2015 at 15:27
  • 1
    And what should id have? Do you want the min(id) too? The id from the row with the min(name)? Something else? Commented Aug 11, 2015 at 15:28

2 Answers 2

4
select id,
       refid,
       name
  from (select id, 
               refid,
               name,
               row_number() over(partition by refid order by name) as rn
          from my_table)
 where rn = 1
 order by id
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a subquery to do this.

WITH Q AS 
( SELECT MIN(NAME) AS NAME, REFID FROM T GROUP BY REFID )
SELECT T.ID, T.REFID, T.NAME
FROM T
JOIN Q 
  ON (T.NAME = Q.NAME)

Also, note that SQL tables have no order. So there's no "First" value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.