Helo每个人!我试图找到网站上先前提出的问题的解决方案,但我发现它们都没有与我的相关,我需要帮助,如何选择表中同一行的九个之间的七个得分标记,其中有高分,并将它们作为如下所示。
name | math | geography | history | pds | ict | civics | social | vskil | french
Joseph 100 90 80 84 70 40 70 90 70
所以这里应该选择以下七(7)个标记(100 + 90 + 80 + 84 + 70 + 90 + 70)。
请帮助。
答案 0 :(得分:1)
您需要将列转换为行,然后进行选择
您可以尝试此查询
select sum(grade) from (
(select math as 'grade' from table1 where name = 'Joseph')
union all
(select geography from table1 where name = 'Joseph')
union all
(select history from table1 where name = 'Joseph')
union all
(select pds from table1 where name = 'Joseph')
union all
(select ict from table1 where name = 'Joseph')
union all
(select civics from table1 where name = 'Joseph')
union all
(select social from table1 where name = 'Joseph')
union all
(select vskil from table1 where name = 'Joseph')
union all
(select french from table1 where name = 'Joseph')
) as x
order by grade desc
limit 7
答案 1 :(得分:1)
使用以下表结构而不是当前表结构,您可以获得更好的性能,使用更少的存储并使代码更容易编写。
表学生:
id integer primary key
name varchar
表科目
studentid integer primary key references students(id)
subject varchar
marks int
真正的优化意味着主题表和主题标记表。有关详细信息,请阅读数据库规范化。
针对特定学生的这种结构,
SELECT SUM(marks)
FROM (SELECT marks FROM subjects WHERE studentid=some_number ORDER BY marks DESC limit 7) AS a
给出给定学生的前7个子喷气机的标记。