[英]How to select single row where one field is different? SQL Server
I have a table like below:我有一张如下表:
ID NAME SCHOOL GRADUATIONYEAR DEGREE MAJOR
--------------------------------------------------------------------------------------------------
100 Ben University1 2015 Bachelor of Arts Major1
100 Ben University1 2015 Bachelor of Arts Major2
100 Ben University2 2017 Master of Science Major3
Since Ben has two records that are from the same university due to double majors (as you can see same School, graduation year, and degree), I only want to pull one of those records rather than both of those records, it doesn't matter which Major I pull, just has to be one instead of both of those records.由于 Ben 有两条记录来自同一所大学,因为双专业(如您所见,您可以看到相同的学校、毕业年份和学位),因此我只想提取其中一个记录而不是这两个记录,它不会无论我拉哪个少校,都必须是一个而不是两个记录。 So ideally, I'd like for it to be like below:
所以理想情况下,我希望它如下所示:
ID NAME SCHOOL GRADUATIONYEAR DEGREE MAJOR
--------------------------------------------------------------------------------------------------
100 Ben University1 2015 Bachelor of Arts Major1
100 Ben University2 2017 Master of Science Major3
I have tried to do a delete like below, but this ends up deleting all of the records, is it possible to maybe use CASE in this scenario?我试图做一个像下面这样的删除,但这最终删除了所有的记录,在这种情况下是否可以使用 CASE?
DELETE FROM #table1
WHERE ID = ID AND NAME = NAME AND SCHOOL = SCHOOL AND DEGREE = DEGREE
Use row_number()
:使用
row_number()
:
select *
from (
select
t.*,
row_number() over(
partition by name, school, graduationyear, degree
order by major
) rn
from mytable t
) t
where rn = 1
When two rows have the same ame, school, graduation year and degree, the query retains the one with the smallest major
, alphabetically-wise (you can change the order by
clause of row_number()
if you want another criteria).当两行具有相同的火焰,学校,毕业年份和程度,查询保留了一个具有最小
major
,按字母顺序明智的(你可以改变order by
的第row_number()
如果你想另一个标准)。
If you wanted a delete
statement:如果你想要一个
delete
语句:
with cte as (
select row_number() over(
partition by name, school, graduationyear, degree
order by major
) rn
from mytable
)
delete from cte where rn > 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.