【问题标题】:How to select records with parent child relation having maximum score for a parent如何选择具有父子关系的记录对父级具有最高分数
【发布时间】:2014-06-16 11:56:59
【问题描述】:

我有这样的表格:

ExerciseAttempt(attemptId, ExerciseId, Score, studentId)
ExerciseMeta(ExerciseId, ParentId)

每个练习都有一个家长。父母可以有很多孩子练习。现在我想找到只考虑父母的一个孩子(得分最高的那个)的记录。

例如:

ExericeAttempt:

attemptId | ExerciseId | Score | studentId
1         | 10         |  18   | 10001
2         | 11         |  12   | 10001
3         | 12         |  20   | 10001
4         | 13         |  22   | 10001
5         | 13         |  21   | 10001

ExerciseMeta:

ExerciseId | ParentId
10         |  100
11         |  100
12         |  101
13         |  101

对于这些表格,结果应该是

attemptId | ExerciseId | Score | studentId
1         | 10         |  18   | 10001
4         | 13         |  22   | 10001

同样可以多次尝试同一个练习。 如何在 SQL SERVER 中实现这一点?

【问题讨论】:

    标签: sql-server sql-server-2008 greatest-n-per-group


    【解决方案1】:
     ;with x as (
        select ea.*, em.parentid,
        row_number() over(partition by parentid order by score desc) as rn
        from ExericeAttempt ea
        inner join ExerciseMeta em
        on ea.ExerciseId = em.ExerciseId
    )
    select attemptId, ExerciseId, Score, studentId
    from x
    where rn = 1
    

    结果:

    ATTEMPTID   EXERCISEID  SCORE   STUDENTID
    1           10          18      10001
    4           13          22      10001
    

    结果为@​​987654321@。

    【讨论】:

    • (+1) 顺便说一句,冒昧地添加结果和小提琴。
    • @RagingBull at:dean for sqlfiddle.com/#!3/ab78c/1 这条记录不起作用
    • “它不工作”是什么意思?这些数据的预期结果是什么?
    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 2015-12-04
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多