我有一个表格"MARK_TABLE"
如下。
如何删除具有相同"STUDENT"
,"COURSE"
和"SCORE"
值的行?
| ID | STUDENT | COURSE | SCORE |
|----|---------|--------|-------|
| 1 | 1 | 1 | 60 |
| 3 | 1 | 2 | 81 |
| 4 | 1 | 3 | 81 |
| 9 | 2 | 1 | 80 |
| 10 | 1 | 1 | 60 |
| 11 | 2 | 1 | 80 |
现在我已经过滤了要保留的数据,但是没有"ID"
...
SELECT student, course, score FROM mark_table
INTERSECT
SELECT student, course, score FROM mark_table
输出:
| STUDENT | COURSE | SCORE |
|---------|--------|-------|
| 1 | 1 | 60 |
| 1 | 2 | 81 |
| 1 | 3 | 81 |
| 2 | 1 | 80 |
答案 0 :(得分:3)
使用以下查询删除所需的行:
DELETE FROM MARK_TABLE M
WHERE
EXISTS (
SELECT
1
FROM
MARK_TABLE M_IN
WHERE
M.STUDENT = M_IN.STUDENT
AND M.COURSE = M_IN.COURSE
AND M.SCORE = M_IN.SCORE
AND M.ID < M_IN.ID
)
输出
干杯!
答案 1 :(得分:0)
使用distinct
SELECT distinct student, course, score FROM mark_table
答案 2 :(得分:0)
select * from
(
select row_number() over (partition by student,course,score order by score)
rn,student,course,score from mark_table
) t
where rn=1
答案 3 :(得分:0)
假设您不只是想要选择要保留的唯一数据(您提到已经完成了此操作),则可以按以下步骤进行操作:
答案 4 :(得分:0)
将CTE与RowNumber一起使用
create table #MARK_TABLE (ID int, STUDENT int, COURSE int, SCORE int)
insert into #MARK_TABLE
values
(1,1,1,60),
(3,1,2,81),
(4,1,3,81),
(9,2,1,80),
(10,1,1,60),
(11,2,1,80)
;with cteDeleteID as(
Select id, row_number() over (partition by student,course,score order by score) [row_number] from #MARK_TABLE
)
delete from #MARK_TABLE where id in
(
select id from cteDeleteID where [row_number] != 1
)
select * from #MARK_TABLE
drop table #MARK_TABLE