为每个类别中的每n条记录分配一个新组

时间:2019-04-01 17:02:23

标签: tsql

我需要为每个类别中的每n条记录创建一个组。例如,我有一个带有StdId,Gen​​der和Subject的学生表,现在我想按性别和科目将所有学生按组划分,每个组不能超过两个。

这是示例数据的代码

extend

我需要这样的输出:

class myDate extends Date{
    constructor(d){
        super(d)
        this.originalInput = d  // save input
    }
    myTest() {
        console.log("original input:",  this.originalInput);
        return 'ok';
      };
}

let dt = new myDate("2019-03-31")
// log the original input:
dt.myTest();

// you can still use `Date` methods:
console.log(dt.toDateString())


let badDate = new myDate("what should I do with bad input")
badDate.myTest();
console.log("Date string:", badDate.toDateString())

1 个答案:

答案 0 :(得分:0)

好吧,在this的帮助下找到了我的解决方案

;with FirstRank as 
(select DENSE_RANK() over (order by Subj, Gender) as rnk, * from @students),
SecondRank AS
(select (ROW_NUMBER() OVER (PARTITION BY rnk ORDER by gender)-1)
            / 2 as rn,*
    from FirstRank
)
select DENSE_RANK() OVER (ORDER BY rnk,rn) as GrpNo, Subj, Gender, StdId from SecondRank