+------------+-------+---------+---------------+
| STudent_ID | Marks | Subject | EntryPoints |
+------------+-------+---------+---------------+
| 1 | 50 | Maths | 10 |
| 2 | 50 | Maths | 10 |
| 3 | 45 | Maths | 10 |
| 1 | 30 | History | 20 |
| 2 | 30 | History | 20 |
| 3 | 30 | History | 20 |
+------------+-------+---------+---------------+
预期产出:
+------------+-------+---------+---------------+
| student_id | Marks | Subject | TotalPoints |
+------------+-------+---------+---------------+
| 1 | 50 | Maths | 5 |
| 2 | 50 | Maths | 5 |
| 1 | 30 | History | 6.66 |
| 2 | 30 | History | 6.66 |
| 3 | 30 | History | 6.66 |
+------------+-------+---------+---------------+
总积分计算
对于数学,入学点数为10,学生得分最大数为2,因此10/2 = 5 历史记录入口点数为20,学生得分最大值为3,因此20/3 = 6.66
我试过查询:
select student_id,marks,subject from
(
select student_id,marks,subject,dense_rank() over ( partition by subject order by marks desc) rn from test
) t
where rn=1
输出:
+------------+-------+---------+
| Student_id | Marks | Subject |
+------------+-------+---------+
| 1 | 50 | Maths |
| 2 | 50 | Maths |
| 1 | 30 | History |
| 2 | 30 | History |
| 3 | 30 | History |
+------------+-------+---------+
我无法获得如何获取查询中的总分数列
答案 0 :(得分:1)
我假设最高分是所有具有相同主题的分数中的最大分数。
SELECT
Student_ID
,Marks
,T.Subject
,CONVERT(decimal(18, 2),
CONVERT(float, EntryPoints)/
CONVERT(float, COUNT(*) OVER(PARTITION BY T.Subject))) as 'TotalPoints'
FROM @T T
INNER JOIN (SELECT DISTINCT Subject, MAX(Marks) OVER(PARTITION BY Subject)
as Max_Marks FROM @T) Scores
ON T.Subject = Scores.Subject
WHERE Marks = Scores.Max_Marks
ORDER BY Marks DESC, Student_ID
答案 1 :(得分:0)
您可以在查询中使用Group by
获取主题计数,然后使用相同的查询join
结果。
如下: -
Select a.student_id,a.marks,a.subject,
Cast(a.EntryPoints as decimal ) / cast(b.CountPerSubject as decimal) TotalPoints
from
(
select student_id,marks,subject ,EntryPoints
from
(
select student_id,marks,
subject, EntryPoints,
dense_rank() over ( partition by subject order by marks desc) rn
from test
) t
where rn=1
) a
Left Join
(
select subject, count(subject) CountPerSubject
from
(
select student_id,marks,subject ,EntryPoints
from
(
select student_id,marks,
subject, EntryPoints,
dense_rank() over ( partition by subject order by marks desc) rn
from test
) t
where rn=1 ) c
group by subject) b
on a.subject = b.subject