答案 0 :(得分:1)
由于您似乎并不在乎需要返回哪个“分支”,因此您只需在row_number
中使用CTE
就可以为每个ID
值仅返回一个结果:
declare @t table(ID int,Name varchar(20));
insert into @t values
(10,'Manoj (CS)')
,(10,'Manoj (IS)')
,(20,'Ajay (CS)')
,(20,'AJAY (IS)')
,(30,'Sunjay(EC)')
,(40,'Lina(IS)')
,(40,'Lina(CS)')
,(40,'Lina(EC)')
,(50,'Mary(IS)')
,(50,'Mary(EC)');
with d as
(
select ID
,Name
,row_number() over (partition by ID order by Name) as rn
from @t
)
select ID
,Name
from d
where rn = 1;
输出:
+----+------------+
| ID | Name |
+----+------------+
| 10 | Manoj (CS) |
| 20 | Ajay (CS) |
| 30 | Sunjay(EC) |
| 40 | Lina(CS) |
| 50 | Mary(EC) |
+----+------------+
但是,如果您确实偏爱(CS)
分支,则需要稍微更改row_number
:
with d as
(
select ID
,Name
,row_number() over (partition by ID
order by case when right(Name,4) = '(CS)'
then 1
else 2
end
,Name
) as rn
from @t
)
select ID
,Name
from d
where rn = 1;
答案 1 :(得分:1)
您可以将row_number()
函数与TIES
一起使用:
select top (1) with ties *
from table t
order by row_number() over (partition by id order by name);
答案 2 :(得分:0)
如评论中所述:更改数据模型。
如果您必须原样使用表格,那么您需要做的就是:所有学生ID,每个学生ID都随意选择了一个麸皮/对象名称。这可以通过简单的聚合来实现:
select id, min(name) from mytable group by id;