1

I have following data in the table.

Id   Name
1    Abc
2    Abc
3    Xyz
4    Xyz
5    def
6    def

I want following results from the query

Id  Name
1   Abc
2   Xyz
3   def

I want to avoid duplicates in the name column.

Any help is greatly appreciated.

Select distinct 
    id, name 
from table A 

will not work as ids are having a different values.

2
  • 1
    Your desired output doesn't make sense. You have ID 2 associated with Xyz, but in the source data it's associated with Abc. Similarly with ID 3 and def. What is the purpose of your query? Commented Nov 11, 2014 at 18:06
  • Are you sure that Xyz isn't supposed to be matched to 3 and Def with 5? Commented Nov 11, 2014 at 18:09

2 Answers 2

2

Use a group by instead.

select
  min(id), [name]
from
  tableA
group by [name]

Note that in your example, the ids that corresponds with Xyz are 3 and 4, so getting a 2 next to Xyz is only possible if you break the integrity of the table. If you are just looking for an auto number next to the ids you can do this:

SELECT row_number() OVER (ORDER BY min(id)) id,
       name 
  FROM tableA
group by name
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. row_number query is what I needed.
0

You can get your specific result using:

select row_number() over (order by min(id)) as id, name
from table A
group by name;

Renumbering the rows seems strange, but row_number() will do that.

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.