簡體   English   中英

從列表獲取自定義不同值

[英]Get custom Distinct Values from column table

表數據和預期數據如下

在此處輸入圖片說明

我想選擇不同的ID和名稱,而與分支無關。 但是我希望顯示分支名稱。 如果不需要顯示分支,則可以使用子字符串。 可以使用CTE實現結果。

由於您似乎並不在乎需要返回哪個“分支”,因此您只需在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;

輸出:

+----+------------+
| 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;

您可以對TIES使用row_number()函數:

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

如注釋中所述:更改數據模型。

如果您必須按原樣使用表格,那么您需要做的是:所有學生ID,每個學生ID都可以隨意選擇一個麩皮/對象名稱。 這可以通過簡單的聚合來實現:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM