如何删除三个相同数据列和一个不同数据列的行

How to delete the rows with three same data columns and one different data column

我有一个 table "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   |

使用distinct

SELECT distinct student, course, score FROM mark_table
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

假设您不只是想 select 您想要保留的唯一数据(您提到您已经这样做了),您可以按以下步骤进行:

  1. 创建一个临时文件table 来保存您要保留的数据
  2. 将要保留的数据插入临时table
  3. 清空来源table
  4. Re-Insert你要保存到源中的数据table。

使用以下查询删除所需的行:

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
    )

输出

db<>fiddle demo

干杯!!

对 RowNumber 使用 CTE

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