[英]Selecting distinct values from table using two columns
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. 由于ID具有不同的值,因此无法使用。
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. 请注意,在您的示例中,与Xyz
对应的id是3和4,因此只有在破坏表的完整性的情况下,才能在Xyz
旁边添加2。 If you are just looking for an auto number next to the ids you can do this: 如果您只是在ID旁边查找自动编号,则可以执行以下操作:
SELECT row_number() OVER (ORDER BY min(id)) id,
name
FROM tableA
group by name
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. 重新编号行似乎很奇怪,但是row_number()
可以做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.