简体   繁体   English

从列表获取自定义不同值

[英]Get custom Distinct Values from column table

Table data and expected data as below 表数据和预期数据如下

在此处输入图片说明

I wanted to select the distinct ID and Name, irrespective of branch. 我想选择不同的ID和名称,而与分支无关。 But I want the branch name to be displayed. 但是我希望显示分支名称。 If branch need not be displayed I can use substring. 如果不需要显示分支,则可以使用子字符串。 Can the result be achieved using CTE. 可以使用CTE实现结果。

As you don't appear to care about which 'branch' needs to be returned, you can simply use a row_number within a CTE to return just one result per ID value: 由于您似乎并不在乎需要返回哪个“分支”,因此您只需在CTE使用row_number即可为每个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;

Output: 输出:

+----+------------+
| ID |    Name    |
+----+------------+
| 10 | Manoj (CS) |
| 20 | Ajay (CS)  |
| 30 | Sunjay(EC) |
| 40 | Lina(CS)   |
| 50 | Mary(EC)   |
+----+------------+

If you do have a preference for the (CS) branch however, you would need to alter the row_number slightly: 但是,如果确实喜欢(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;

You can use row_number() function with TIES : 您可以对TIES使用row_number()函数:

select top (1) with ties *
from table t
order by row_number() over (partition by id order by name);

As mentioned in the comments: Change your datamodel. 如注释中所述:更改数据模型。

If you must live with the table as is, all you want is: all student IDs, each with one branhc/subject name arbitrarily picked. 如果您必须按原样使用表格,那么您需要做的是:所有学生ID,每个学生ID都可以随意选择一个麸皮/对象名称。 This can be achieved with a simple aggregation: 这可以通过简单的聚合来实现:

select id, min(name) from mytable group by id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM