2

我在下面有这个特殊的表格。我想从第 2 组中删除重复的课程,因为它在第 1 组中。基本上,如果课程映射到第 1 组,这是强制性的,我们必须只考虑这一点,而不是在任何其他组中。我必须先检查重复课程,然后删除非强制性的重复课程。


    Program   Group Course     Mandatory
     Program1   1   a          YES
     Program1   1   b          YES
     Program1   1   c          YES
     Program1   2   d          NO
     Program1   2   a          NO
     Program1   2   e          NO
     Program1   3   f          YES  

我无法弄清楚相同的列操作,或者我的思维今天不工作(:-))我尝试使用计数操作并为重复行创建标志,但不能在 group by 子句中使用“Group” .

输出:

    Program   Group Course     Mandatory
     Program1   1   a          YES
     Program1   1   b          YES
     Program1   1   c          YES
     Program1   2   d          NO
     Program1   2   e          NO
     Program1   3   f          YES  

编辑

我们如何检查重复记录并将其从一个特定组中删除。

4

2 回答 2

3

您可以使用 ROW_NUMBER() 函数来实现此目的:

SELECT *
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY COURSE ORDER BY [Group] ) as RowRank
      FROM table
     )sub
WHERE RowRank = 1

演示:SQL 小提琴

编辑:ROW_NUMBER 为每一行分配一个数字。对于您通过该部分分配的每个分组,编号将从 1 开始PARTITION BY,在这种情况下,每个分组COURSE都有一个数字 1 并上升。数字的顺序由ORDER BY部分决定,在这种情况下,最低[Group]的获得 1。

于 2013-06-26T20:04:52.457 回答
1

编辑我的答案以反映明确的要求。

select *
from @TableName t
where 
    (Mandatory = 'YES' or 
    not exists (
        select * 
        from @TableName 
        where 
            Program = t.Program and 
            Course = t.Course and 
            [Group] != t.[Group] and 
            Mandatory = 'YES'
    ))

根据您在下面的评论,这是另一个可以尝试的示例

;with group1 as (
    select * from @Table where [Group] = 1
),
groups12 as (
    select * from group1
    union all
    select * from @Table t where [Group] = 2 and not exists (select * from group1 where Program = t.Program and Course = t.Course)
),
groups123 as (
    select * from groups12
    union all
    select * from @Table t where [Group] = 3 and not exists (select * from groups12 where Program = t.Program and Course = t.Course)
),
groups1234 as (
    select * from groups123
    union all
    select * from @Table t where [Group] = 4 and not exists (select * from groups123 where Program = t.Program and Course = t.Course)
)
select * from groups1234

此查询按顺序提取组 1-4 的行,并且仅当程序/课程尚未出现在较低编号的组中时。

于 2013-06-26T20:14:14.633 回答