我有一张带有此数据的表
+------+-----+————-----+
|Props |Score|Type |
+------+-----+-------- +
|1.EY | 30|Core
|2.FG | 29|Core
|2.YUE | 29|Core
|3.VB. | 28|Elective
|4.RX. | 67|Elective
|5.XE. | 89|Elective
|6.TF. | 60|Elective
|7.HK | 76|Elective
|8.ER | 58|Elective
我想通过将所有核心分数加三个最佳选修分数中的任何一个相加来计算总体分数。我似乎找不到解决方法。
预期结果为320:3核心得分+ 3最佳选修课 即(30 + 29 + 29)+(89 + 76 + 67)
答案 0 :(得分:1)
您可以在内部查询的类型分区中按类型对记录进行排名,并在外部查询中进行条件求和,例如:
SELECT
SUM(CASE
WHEN type = 'Core' THEN score
WHEN type = 'Elective' AND rn <= 3 THEN score
ELSE 0
END) res
FROM (
SELECT
t.*,
ROW_NUMBER() OVER(PARTITION BY type ORDER BY score DESC) rn
FROM mytable t
) x
Demo on DB Fiddle with your sample data :
| res |
| --- |
| 320 |
答案 1 :(得分:1)
对2种情况使用UNION ALL,然后对返回的分数求和:
select sum(t.score) totalscore
from (
select score from tablename
where type = 'Core'
union all
select t.score from (
select score from tablename
where type = 'Elective'
order by score desc
limit 3
) t
) t
请参见demo。
结果:
| totalscore |
| ---------- |
| 320 |